Reputation: 433
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
Upvotes: 2
Views: 3198
Reputation: 104379
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);
})
Upvotes: 7