In this chapter, I’ll explain the difference between axios and fetch. Both methods are used to get data from a backend server. Axios is a much more preferred method to be used to fetch data and below is why!

Fetch

function main() {
    fetch("<https://jsonplaceholder.typicode.com/users/1>")
    .then(async response => {
        const json = await response.json();
        console.log(json.name.length);
    })
}

async function main2() {
    const response = await fetch("<https://jsonplaceholder.typicode.com/users/1>");
    const json = await response.json();
    console.log(json);    

}

main2();
main();

These are the two methods to use fetch using the .then syntax or async-await syntax.

Let’s breakdown what is exactly happening,

Lets write the same fetch mechanism with axios.

const axios = require('axios');

async function axiosFunc() {
    const response = await axios.get("<https://jsonplaceholder.typicode.com/users/1>");
    console.log(response.data);
}

axiosFunc();

Firstly, axios is not available natively in react, hence we have to install it using command npm install axios, once that is done we set it to a variable using the require() function.

Let’s break this down as well,

POST Request Comparison

In order to POST a request in Fetch and Axios, there is a change in the syntax which I will show in the code.

For Fetch,