Step 8

We will use the browser's localstorage to add persistence. Update the App.js as follows:

  1. Add a saveNotes method to the App component:
saveNotes = () => {
  window.localStorage.setItem("notes", JSON.stringify(this.state.notes));
};
  1. Update the addNote, editNote, and deleteNote methods to call saveNotes once the state is updated. Notice how the saveNotes is provided as a callback argument to the setState 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);
  };
  1. 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.