My local storage is not saving after page refresh

Viewed 598

I am new at this and I am creating a note app, but the new notes that I add are not being saved on the Local Storage. It does appear on the Application but when the page is refreshed, it disappears. Where am I getting it wrong?

        const savedNotes = JSON.parse(
            localStorage.getItem('notes-app-data')
        );

        if (savedNotes) {
            setNotes(savedNotes);
        }
    }, []);

    useEffect(() => {
        localStorage.setItem(
            'notes-app-data',
            JSON.stringify(notes)
        );
    }, [notes]);```
3 Answers

Try this:

const [savedNotes] = useState(localStorage.getItem('notes-app-data'))
const [notes, setNotes] = useState(
        savedNotes ? JSON.parse(savedNotes) : []
)

useEffect(() => {
    localStorage.setItem("notes-app-data", JSON.stringify(notes))
}, [notes]);

I assume the variable notes is defined using useState with an initial value of null.

This would mean that your useEffect hook is being called on page refresh, and then you are setting your notes-app-data item to null, effectively deleting it.

You can fix this by ensuring notes is not null before using setItem, for example

useEffect(() => {
 if(!!notes) {        
  localStorage.setItem(
   'notes-app-data',
    JSON.stringify(notes)
  );
 } 
}, [notes]);

This answer helped me, https://stackoverflow.com/a/71961318/16282690

Delete this code:

    const savedNotes = JSON.parse(
        localStorage.getItem('notes-app-data')
    );

    if (savedNotes) {
        setNotes(savedNotes);
    }

and try this but declare it out of function scope

const savedNotes = localStorage.getItem('notes-app- 
data')
? JSON.parse(localStorage.getItem('notes-app- 
data')) : [];

then update useState:

const [notes, setNotes] = useState(savedNotes)
Related