Home > Mobile >  Saving information to localStorage, but localStorage is not saving it on refresh (React.js)
Saving information to localStorage, but localStorage is not saving it on refresh (React.js)

Time:12-06

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]);

CodePudding user response:

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

CodePudding user response:

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

  • Related