2

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 1

1

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);
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

where to put that common api call in my project so that it can be called automatically before any other api call ?
@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.
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.

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.