DEV Community

Do you use Axios or Fetch?

Jasterix on August 12, 2019

As a lover of all things programming, I send a lot of time exploring why we follow certain conventions. More recently, I've been playing around w...
Collapse
 
antonioavelar profile image
António Avelar • Edited

There's one thing i find annoying when working with axios (the only module im using right now).
So i have a stack wich consists of a react web app + Node.js/Express REST api. Whenever i send a json response from my api and i need to read it in my front-end application i have to access it this way:

// response from api
// { success: true, data : [1,2,3,4,5,6,7] }

axios({...})
  .then((res) => {
     if ( res.success && res.data ) {
       //the data is in res.data.data
     }
  })
Enter fullscreen mode Exit fullscreen mode

This thing happens because axios wraps all the response from the server inside response['data']. So if you're going to use the normal rest convention on your api responses you will need to access it like response['data']['data'] or like response.data.data .

Collapse
 
anwar_nairi profile image
Anwar • Edited

I just came into 2 things that should interest you (and me as well!) :

transformResponse

This is a configuration option in axios that can let us fix this behavior by returning the plain server response:

axios.get("/users", {
  transformResponse: [
    function(data) {
      return data.data;
    }
  ]
});
Enter fullscreen mode Exit fullscreen mode

I find it a bit ugly to have an array of functions...

Interceptors response

Might be a more elegant way to fix it. Plus, you do not have to add it in your configuration for every request, it is done once and for all.

axios.interceptors.response.use(function (response) {
  return response.data;
});
Enter fullscreen mode Exit fullscreen mode

I will try it and if it works, I might start using it again in my projects :)

Collapse
 
antonioavelar profile image
António Avelar

Thanks for your advice. That's a nice way of doing it.
I already use interceptors for listening for the 401 response status.

Although i said that's something annoying the verbosity of axios is at the same time where axios shines. We can take as an advantage the verbosity of the response and use it to enrich our logs

Thread Thread
 
jasterix profile image
Jasterix

I've been reading about Axios interceptors and it seems like a cool way to address not only HTTP errors but async problems that can pop up

Thread Thread
 
antonioavelar profile image
António Avelar

You're right! You can also use request interceptors to add custom headers like an authorization token in every single request, removing the need to write repetitive code

Collapse
 
tbhaxor profile image
Gurkirat Singh

You can use destructuring of the response object

// response from api
// { success: true, data : [1,2,3,4,5,6,7] }

axios({...})
  .then(({ body, ...res }) => {
     if ( body.success ) {
       console.log(body.data)  // [1,2,3,4,5,6,7]
     }
  })
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anwar_nairi profile image
Anwar • Edited

I personnaly use fetch because of 2 reasons:

  1. I did not understood why by default data were returned in a data key
  2. I did not find its value over the regular fetch

Now, for 4kb more in our client bundle, this makes a pretty good tool to add in our toolbelt...

Collapse
 
haritsinh profile image
Haritsinh Gohil

There are 2 reasons to use axios over fetch

  1. Using fetch() there is a two-step process when handing JSON data. The first is to make the actual request and then the second is to call the .json() method on the response, where on axios you get json response by default.

  2. And second issue with fetch() is it does not handle exceptions as intended, it does not enter in catch block when error occurs but axios works as expected in error handling.

see this medium article for details and example: fetch vs axios

Collapse
 
anwar_nairi profile image
Anwar

Months have past, and I finally switched my fetch call for axios call. So much better indeed, and I found a way to overcome issue 1. I mentioned.

What made me make do the refractor is the fact that fetch would not throw proper exception if the error code were different than 200, I manually need to check if response.ok. So axios is my go to http request tool now 🤓

Collapse
 
jasterix profile image
Jasterix

Thanks for the concise explanation! I'll check out the blog post you shared

Collapse
 
tbhaxor profile image
Gurkirat Singh

Well the question should be "Do you use fetch or xhr?"

So if your platform has to only deal with plain text related requests with promise support, I would recommend and myself use fetch.

But everyone know that's not the case, in every web platform there is a case we have to integrate ajax and stream uploads and downloads. The fetch here fails to implement the logic. So here I would recommend and use ajax.

Now there are too many libraries implementing ajax under the hood, two of them are the most popular one. Jquery and Axios.

When you want to promises and easily maintainable code, I would prefer Axios and Jquery otherwise.

Collapse
 
michaelbrooks profile image
Michael Brooks

I had this discussion recently as I've started to use fetch instead of Axios. The general responses were about browser support as Axios is compiled with Babel and will, therefore, work on more browsers then fetch will.

Also, Axios can give you progress updates on post requests and apparently has better security (I'm personally not sure on that one).

Collapse
 
simonhaisz profile image
simonhaisz

Yup. If you need to support IE or really old Android/iOS Axios is a good answer, though there are polyfills just for fetch if you want to go that way.

Collapse
 
bryanleetc profile image
Bryan Lee

A mixture of both, Axios because they're already being used in several of the existing projects I'm working on. I recently started work on a brand new spanking project and for that fetch was chosen because it's supported by all our target browsers. One less dependency is always better!

Collapse
 
joshualoran profile image
Joshua M Loran

I use fetch unless axios is in an existing project. I also saw this article on reddit the other day. Axios project doesn't seem to be managed well and therefore may not be the tool of choice sooner than later.

I'm in the "less packages more better" camp also

Collapse
 
jonasws profile image
Jonas Strømsodd

If I know I am going to use Cypress, I choose Axios, since spying/asserting on fetch calls is not supported yet, else I usually choose fetch!

Collapse
 
crycetruly profile image
cryce truly

I have faced an issue with fetch and cypress, Am now rewriting my existing code to use Axios.

Collapse
 
michaelrice profile image
Michael Rice

I've used Axios in cases by default, forgetting to use fetch. The fewer dependencies the better in my mind, however!

Collapse
 
avalander profile image
Avalander

I use either fetch or node's native http module. The fewer dependencies the better.

Collapse
 
fleepgeek profile image
Emmanuel Okiche

I just published an article on this topic.
Hope you find it helpful.

Collapse
 
kdemetter profile image
De Metter Kenny • Edited

I use Request (github.com/request/request)