I’m creating this project, but I am having trouble learning why my code is not being saved to localStorage upon refresh. When I add stuff to the JSON file it saves properly, but when I reload all of the data from the JSON file disappears.
I have tried many different formats for loading in the information, such as adding other formats in the format string but nothing has seemed to work.
const [notes, setNotes] = useState([
]);
useEffect(() => {
const savedNotes = localStorage.getItem('react-notes-app-data');
if (savedNotes != null) { setNotes(JSON.parse(savedNotes)); }
}, []);
useEffect(() => {
localStorage.setItem(
'react-notes-app-data',
JSON.stringify(notes)
);
setDisplayNotes(notes);
}, [notes]);
2
Answers
Try initializing your useState like this
And get rid of your entire first useEffect call. Basically there’s a logical error where you’re always setting localStorage to an empty array on load
Notes must be a new object to trigger the useEffect as it doesn’t do deep checking.
I have created an example and tested it. It works fine. However, @ceckenrode has suggested better way.
https://codesandbox.io/s/silly-water-jiwi6x?file=/src/App.js