skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search