0

I'm saving user data to localStorage in login component and then redirecting to the profile page. In profile page username in not updating on first visit. I have to reload the page. How can I show data on first visit?

Jessica
  • 1
  • 2

3 Answers3

0

Use Redux to store the data that you have updated and connect your component with redux state to get an updated value.

For more info about redux refer this link:

https://redux.js.org/basics/usage-with-react

Dishant Desai
  • 154
  • 2
  • 7
0

While localStorage.setItem may not be async, it does not guarantee that the data is written to the storage before the navigation to profile page happens. So, when you try to read the localStorage for that key, it may still be null (or the old value).

One workaround is to delay the navigation to Profile page by a few hundred milliseconds. Or, do not solely depend on the localStorage to read the data for the first time.

dp.js
  • 111
  • 2
  • Found a discussion on this in an older post. Maybe helpful @Jessica [https://stackoverflow.com/questions/20231163/is-html5-localstorage-asynchronous] – dp.js Jul 30 '20 at 06:00
0

localStorage and sessionStorage changes won't be applied to you application unless your reload your page. you have 2 ways:

  1. reload page by using: (Easy simple and fast but UGLY!)

    window.location.reload();

  2. save and update your data in react context (Highly recommended) Use this docs to read about it: https://reactjs.org/docs/context.html

  3. save and update your data in react redux. Use this docs to read about it: https://react-redux.js.org/introduction/basic-tutorial

Hossein Ahmadi
  • 444
  • 4
  • 9