Skip to content
Advertisement

Axios instance not getting the token from local storage on first call – React js + django

I created an Axios instance to set up the baseURL and the headers. The header also needs to contain the token for authorization. So when a user logs in I call an API to fetch some data related to the user using useEffect. So the API gets called immediately after the login is completed. This API needs permissions and hence requires the token. On login, I store the token in local storage but for some reason, the token is not loaded on the first call of the instance and I get an Unauthorised error from the backend. But then if I manually reload the page, the API gets called again but this time the token is received by the instance and the data is fetched. Below is my code.

axios instance

JavaScript

api call

JavaScript

I followed a youtube video to learn this, he is not getting this error but for some reason I am getting this error. Please suggest to me what should I do.

Update

code to show where I store the token in the local storage

action that stores the token and user details in redux

JavaScript

userLogin() API code

JavaScript

mocking value of the response.data received int the above function

JavaScript

Advertisement

Answer

Your issue probably happens because you set the axios instance token on the application startup, but never update it upon login.

You would need to “refresh” the value when a login happens by checking again for the localStorage data.

A quick solution would be to calculate the headers every time you call the API

JavaScript

And then in the API call

JavaScript

Another solution would be mutating the axios instance when a login happens by doing something like this

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement