Skip to content
Advertisement

ReactJS: Unable to retrieve properly localStorageItem after navigate to another component

I have this scenario that is after the user login and assuming it is success, user details / user token is stored to localStorage and will automatically navigate to dashboard page, dashboard page has some api calls and those api calls required/needs token that is stored in the localStorage, my problem is that it is unable to retrieve those values in localStorage, but when I check from localStorage using console, the key/value is there, I noticed that, I need to refresh the page to retrieve those details without a problem. How can I possibly fix this issue? to be able to get localStorage value after navigating to another component?

Here is my code for index.tsx

JavaScript

AuthContext code:

JavaScript

App.tsx code

JavaScript

Login code:

JavaScript

Dashboard code:

JavaScript

Dashboard service code:

JavaScript

Auth-header code:

JavaScript

Advertisement

Answer

The problem is that the check to localStorage in AuthHeader() isn’t updating reactively. The fix would be to rewrite AuthHeader to accept the user data like this:

JavaScript

and then continue the data piping into the area where AuthHeader() is called, perhaps like this:

JavaScript

Lastly, using an effect in the dashboard to update it reactively, while connecting to context:

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