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]);
>Solution :
Try initializing your useState like this
let initialNotes;
try {
initialNotes = JSON.parse(localStorage.getItem('react-notes-app-data'));
catch(err) {
initialNotes = [];
}
const [notes, setNotes] = useState(initialNotes);
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