Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading