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!
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,
.fetch has been used to set the endpoint..json() format.json and finally logging it.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,
axios.get(). One can also perform POST PUT DELETE using the same syntax..json step anymore and neither are we awaiting it.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,