DEV Community

Cover image for How To Use Axios in an Optimized and Scalable Way With React

How To Use Axios in an Optimized and Scalable Way With React

Nilanth on July 14, 2021

We can see how to use Axios in an optimized and scalable way in a React app. When you are building an API-based React app, an HTTP client is the c...
Collapse
 
leandro_nnz profile image
Leandro Nuñez

This is truly useful. Thanks a lot.

Collapse
 
alexstaroselsky profile image
Info Comment hidden by post author - thread only accessible via permalink
Alexander Staroselsky • Edited

What is the need for then(response => response) on each method? Did you intend to extract data from the response so the consumer doesn't have to grab data each time? Such as return axiosClient.get(/${URL}).then(response => response.data);? Otherwise it could be removed to shorten those wrapper/helper methods.

Collapse
 
nilanth profile image
Nilanth

To access the response like below

import { getRequest } from 'axiosClient';

async function fetchUser() {
try {
  const user = await getRequest('users');
  console.log(user.data);
} catch(error) {
   //Log errors
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alexstaroselsky profile image
Alexander Staroselsky

What happens when you remove .then(response => response) from getRequest(URL). Does it change how const user = await getRequest('users'); works at all?

Collapse
 
nazareth profile image
َ

So good 🙏

Collapse
 
kayodeadechinan profile image
Kayode Adechinan

super useful, thanks

Collapse
 
dualyticalchemy profile image
⚫️ nothingness negates itself

sweet thank you

Collapse
 
tadjerounimohamedadel profile image
Adel Mohamed Tadjerouni

Awesome

Collapse
 
solsen_tl profile image
Steven Olsen

I recommend using fetch everywhere, as axios can become bundle bloat for UIs. You just don't need it, really.

Collapse
 
sajidali2444 profile image
Sajid Ali

exactly you are correct, but how we can use interceptor in fetch ?
personally I like to use fetch

Collapse
 
nurfitrapujo profile image
Nurfitra Pujo Santiko

Awesome

Collapse
 
hussein_rk profile image
HUSSEIN RAGAB🇪🇬

Great article 👏👏

Collapse
 
h3li0 profile image
Helio da Silva Jr.

Amazing article. Super useful. Thank you ! ;-)

Collapse
 
sapkotamadan profile image
Madan Sapkota
axios.interceptors.request.use(function (request) {
  request.headers['Content-Type'] = 'multipart/form-data';
  return request;
}, null, { synchronous: true });
Enter fullscreen mode Exit fullscreen mode

Some comments have been hidden by the post's author - find out more