Destructuring Axios response

Titas Gailius
1 min readMay 28, 2018

--

When you consume some API, more times than not you’re going to encounter a response that has “meta” and “data” properties in it. A perfect example would be a paginated response.

Typically one would jump right into using Axio’s Promise callback and access data like this:

But don’t you think that “response.data.data” looks weird?

How often do you need to access response headers directly on the axios response instance? Most likely never and in this case consider using response interceptors.

axios.interceptors.response.use(response => response.data)

Then axios will resolve the response body right away and you can destruct it in a much more elegant way.

These small things that makes your code look much cleaner and easier to read are my favourite. I hope you enjoyed this little trick.

--

--