DEV Community

Discussion on: You Need to Try These 10 NPM Packages as a React Developer

Collapse
 
nassimmiled profile image
nassimmiled

Why do we use axios when we have fetch?

Collapse
 
geobrodas profile image
Georgey • Edited

Axios comes in handy if you're a Rest-API fan

Collapse
 
promikecoder2020 profile image
ProMikeCoder2020

As some have already said it clmes with better browser support and syntax, but it's biggest advantage is having extra features likr timeout request and others

Collapse
 
itsnitinr profile image
Nitin Ranganath • Edited

Mostly because it is simpler to work with. Here's an example considering that I want to fetch from todos from a sample API:

With fetch:

const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const todos = await response.json();
console.log(todos);
Enter fullscreen mode Exit fullscreen mode

With axios:

const todos = await axios.get('https://jsonplaceholder.typicode.com/todos')
console.log(todos)
Enter fullscreen mode Exit fullscreen mode

Notice how we didn't have to manually convert the response manually to JSON. It's because axios does that automatically for us. This is just one of the features. So yeah, it saves us some time and lines of code.

Collapse
 
Sloan, the sloth mascot
Comment deleted
 
kacperturon profile image
Kacper Turon

well it's not exactly the same, axios comes with backwards compatibility, and polyfills in old browsers, it will work almost everywhere

Collapse
 
clydegrey profile image
Clyde

You used then for one example and async/await for the other. It's better if you want to show a like for like comparison that you stick to the same approach so that you can highlight just the differences between then two. This makes fetch seem more verbose and more difficult to read when most of that is due to await being more concise.

Thread Thread
 
itsnitinr profile image
Nitin Ranganath

You're right. Edited the example to use async-await in both cases. Thanks for notifying.