简体   繁体   中英

Cant retrieve local storage data after a refresh

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


replace

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

with

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM