I am using localStorage to store my data locally. I can see the defined object but when I add a value and then refresh the page, the new added data is lost and is not stored. What could be the problem?
https://codesandbox.io/s/todolistmax-9ng5fx?file=/src/App.js
This is the link to my codesandbox. After refresh, the newly entered data is lost and is not saved.
Thanks!
2
Answers
First, you have a
useEffect
that is always firing and overriding thelocalStorage
. Also, you should save modified course goal inlocalStorage
every time you do an action:Bonus
I reworked some of your modifying code (Codesandbox)
App.js
The problem is that the useEffect hook that saves data to localStorage runs on every state change. To fix it, add an empty dependency array [] as the second argument to the useEffect hook that saves to localStorage. This ensures it runs only once on mount and won’t overwrite your data on subsequent updates.
Without a dependency array, the useEffect hook will run after every render,
so updated useEffect hook is