Step 8
We will use the browser's localstorage to add persistence. Update the App.js
as follows:
- Add a
saveNotes
method to theApp
component:
saveNotes = () => {
window.localStorage.setItem("notes", JSON.stringify(this.state.notes));
};
- Update the
addNote
,editNote
, anddeleteNote
methods to callsaveNotes
once the state is updated. Notice how thesaveNotes
is provided as a callback argument to thesetState
method.
deleteNote = (note) => {
this.setState((state) => {
return {
notes: state.notes.filter((n) => n.id !== note.id),
};
- });
+ }, this.saveNotes);
};
addNote = (note) => {
this.setState((state) => {
return {
notes: [...state.notes, Object.assign(note, { id: uuidv4() })],
};
- });
+ }, this.saveNotes);
};
editNote = (note) => {
this.setState((state) => {
return {
notes: state.notes.map((n) => (n.id === note.id ? note : n)),
};
- });
+ }, this.saveNotes);
};
- Add a
componentDidMount
method to read the state from the local storage.
componentDidMount() {
const notes = window.localStorage.getItem("notes");
this.setState({
notes: notes ? JSON.parse(notes) : [],
});
}
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!
Notice you can open the Developer Tool and inspect the "local storage" under the "Application" tab.