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.
CodePudding user response:
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.
CodePudding user response:
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)