Step 24: Persistence
We will use the browser's localStorage to add persistence.
Update the App.jsx
as follows:
Add this useEffect
to the App
component to save the notes when they are updated:
useEffect(() => {
window.localStorage.setItem("notes", JSON.stringify(notes));
}, [notes]);
Update this useEffect
so instead of making fake random notes, we read them from the localStorage.
useEffect(() => {
- const fakeNotes = [];
- for (let index = 0; index < 5; index++) {
- fakeNotes.push({
- id: faker.datatype.uuid(),
- title: faker.lorem.sentence(),
- text: faker.lorem.paragraph(),
- });
- }
- setNotes(fakeNotes);
+ const storedNotes = window.localStorage.getItem("notes", notes);
+ const initNote = storedNotes ? JSON.parse(storedNotes) : [];
+ setNotes(initNote);
}, []);
Save the file and visit the running app. Try to add, edit, and delete a note. Each time, refresh the page to ensure the state persists!