2

I have an SPA app built in React with many axios calls to an API. I can set up a redirect to the login page within axios when the error status returns 401, but with the large number of calls spread across a lot of components, is there a better way to handle this without repeating the:

if (error.status === 401) {
    //redirect to login page
}

in every single request

1
  • 2
    Sounds like a great job for an interceptor! npmjs.com/package/axios#interceptors Functions you can define that all requests/responses will route through. Recommended way of global error handling when using axios. Commented Jun 5, 2017 at 21:33

1 Answer 1

7

Avoid writing the api calls in all the components, create a separate file api.js or some abc.js, and write a generic method of making calls, and call that method from different component with proper parameters. In that case you need to handle all those kind of cases in every file, just put the logic only at one place inside api.js file.

api.js:

export function _callAPI(url, method, data, target){
     /*
         url: separate url for different component
         method: Get or Post or Put etc
         data: if required to pass
         target: callback method
     */
}

Then import this in different component:

import * as Api from 'path to api.js file';

call that by:

Api._callAPI(url, method, data, (data) => {
    console.log(data);
})
Sign up to request clarification or add additional context in comments.

2 Comments

The biggest concern I am having is the nature of the API calls can have anywhere from 1 to 4 calls for some components (for example the search results + dropdown filters (which autocomplete with db data)). Is there any major loss of speed having a series of calls rather than doing them parallel with axios.all? Right now my architecture has container components loading the api data, then sending that data to its child component as props. It works great, but has very varied needs,
here also you can make the parallel call, write the axios call in this _callAPI method and call that method multiple times, each call be async call and it will be parallel in nature not sync (check browser network part you will see all are fetching data parallelly)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.