DEV Community

Discussion on: Do you use Axios or Fetch?

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