Suppose I want to call an api(for session) before each api call , api should be called automatically before any other api call. How I can achieve this in axios in react. I want to do it globally for whole project.
1 Answer
You can write a wrapper around axios. You should usually do this anyway so that you can inject headers and other things specific to your application.
Here's a basic version of that.
let sessionStuffPromise = null;
function request(method, ...args) {
if (!sessionStuffPromise) {
// do your initial stuff and return a promise
sessionStuffPromise = foo();
}
return sessionStuffPromise.then(() => {
return axios[method](...args);
});
}
3 Comments
NISHANT JAIN
where to put that common api call in my project so that it can be called automatically before any other api call ?
Brigand
@NISHANTJAIN you use this function any time you want to make a request; it automatically ensures the
foo() promise completes before making another request while also not making the foo() request more than once.NISHANT JAIN
Where to put this function ? I want to set some api call globally in axios library that would be called automatically before any api call.