Home > database >  Cant retrieve local storage data after a refresh
Cant retrieve local storage data after a refresh

Time:11-25

Whenever i add or update an object it goes straight to the local storage and it works fine. However when i refresh a page the data stored in LS is being replaced with an empty array. What am i doing wrong?

  const [data, setData] = useState<NoteType[]>([]);

   useEffect(() => {
    setData(JSON.parse(window.localStorage.getItem("notes") || "[]"));
  }, []);

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

  const handleNoteSave = (text: string, id: string) => {
    const updatedNote = data.map((note) => {
      if (note.id === id) {
        return { ...note, text };
      }
      return note;
    });

    setData(updatedNote);
  };

  const handleNoteAdd = () => {
    setData((prevState) => [...prevState, { text: "", id: nanoid() }]);
  };


CodePudding user response:

replace

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

with

useEffect(() => {
    if (data.length > 0) { 
        window.localStorage.setItem("notes", JSON.stringify(data));
    }
  }, [data]);

CodePudding user response:

Both useEffect will be triggered on load, you can load the data from localStorage directly with useState

Then on useEffect data should have something

const [data, setData] = useState<NoteType[]>(() =>  (JSON.parse(localStorage.getItem("notes") ?? "[]") as NoteType[]));

useEffect(() => {
  window.localStorage.setItem("notes", JSON.stringify(data));
[data]);
  • Related