0

My react app will save data to local storage but when refreshed the data disappears. What am I doing wrong with local storage?

    import { useEffect, useState } from "react";
    import { nanoid } from "nanoid";
    import NoteList from "./components/noteList";
    import Search from "./components/search";
    import Header from "./components/header";

const App = () => {
  const [notes, setNotes] = useState([]);

  const [searchText, setSearchText] = useState("");

  useEffect(() => {
    const savedNotes = JSON.parse(localStorage.getItem("notes-data"));

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

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

  const addNote = (text) => {
    const date = new Date();
    const newNote = {
      id: nanoid(),
      text: text,
      date: date.toLocaleDateString(),
    };
    const newNotes = [...notes, newNote];
    setNotes(newNotes);
  };

  const deleteNote = (id) => {
    const newNotes = notes.filter((note) => note.id !== id);
    setNotes(newNotes);
  };

  return (
    <div>
      <div className="container">
        <Header />
        <Search handleSearchNote={setSearchText} />
        <NoteList
          notes={notes.filter((note) =>
            note.text.toLowerCase().includes(searchText)
          )}
          handleAddNote={addNote}
          handleDeleteNote={deleteNote}
        />
      </div>
    </div>
  );
};

export default App;

From everything that I have read I can't see what I'm doing wrong unless its something simple.

This is pre refresh

this is post refresh

  • Does this answer your question? [React, losing saved data in localStorage with useEffect after page refresh](https://stackoverflow.com/questions/73177643/react-losing-saved-data-in-localstorage-with-useeffect-after-page-refresh) – Youssouf Oumar Sep 20 '22 at 07:22

3 Answers3

0

The problem is in the second useEffect hook since it is executing depending on notes array (initially is empty), this causes the localstorage data to be "erased" (in reality it is updated to an empty array after component mounts).

To understand better what I mean add a console log here to see when it is executing and what data is saved.

useEffect(() => {
console.log('saving data to local storage', notes);

localStorage.setItem("notes-data", JSON.stringify(notes));
}, [notes]);

Update:

You can handle that by stoping the useEffect execution on first render (for more information check this question)

Victor
  • 439
  • 3
  • 11
0

That is because of this code snippet useEffect(() => { localStorage.setItem("notes-data", JSON.stringify(notes)); }, [notes]);

Before setting notes-data please check if the localStorage has notes-data already set using localStorage.getItem("notes-data") in an if condition.

0

it's because your react Component is rendering twice and to solve this issue you have to disable the <React.StrictMode> in your index.js file:- For example, you might find that your is wrapped by <React.StrictMode> in your index.js:

 ReactDOM.render(
     <React.StrictMode>
       <App />
     </React.StrictMode>,
  );

If so, you can disable StrictMode by removing the <React.StrictMode> tag:

ReactDOM.render(
    <App />
  );