Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Persisting state on browser reload not working in react

I have checked on blogs and other stack overflow questions for this. The answer is quite simple and clear, but doesn’t seem to work for me. I am using functional component, I tried to use both localStorage and sessionStorage for a simple counting app. The app still works but the count state defaults back to 0 on browser reload instead of the current state in the sessionStorage. I must be missing something or I get this completely wrong…

Here is my code…
Manipulating the count into and from the sessionStorage

// Setting the count to the stored value in localStorage...
  useEffect(() => {
    setCount(JSON.parse(sessionStorage.getItem('count')))
  }, [])

  // setting the local storage every time count changes...
  useEffect(() => {
    sessionStorage.setItem('count', count)
  }, [count])

Handling click events…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// The handlers...
  const plusHandler = () => {
    const newCount = count
    setCount(newCount + 1)
  }

  const minusHandler = () => {
    const newCount = count
    setCount(newCount - 1)
  }

Printing the count using <p>{count}</p>

See the Full CodeSandbox Project Here

Even a short description of what I might be doing wrong will be appreciated…

>Solution :

Call sessionStorage.getItem() outside of useEffect to get the initial state of your counter synchronously:

const [count, setCount] = useState(parseInt(sessionStorage.getItem("count") || 0, 10))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading