I created the axios instance and storing the token in the localStorage at the time of login but for some reasons token is not loaded in the localstorage whenever the api calls and got an error from the backend. But then if i manually reload the page the api gets call and now instance is getting the token and data is loaded and works fine. How to resolve it ????? Here is the code:
export const instance2 = axios.create({
baseURL: 'http://127.0.0.1:8000',
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
I'm using this instance2 in each page but it not works on first attempt.
it is because instance2 is not a function and is not triggered every api call. You should convert that to function.
Example:
export const instance2 = () => {
return axios.create({
baseURL: 'http://127.0.0.1:8000',
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
});
}
Example usage:
instance2().get('url')