Step 11

For editing a note, we must set the initial value of the relevant state (i.e., title and text properties) from the note data, which is passed as state props to the UpsertNote component by the Link component of the react-router library. Naturally, we would want to do this inside the constructor of the UpsertNote component.

constructor(props) {
  super(props);
  this.state = {
    id: this.props.location.state.id || undefined,
    title: this.props.location.state.title || "",
    text: this.props.location.state.text || "",
  };
}

The code snippet above initializes the state if the this.props.location.state exists. Please note that initializing state from props is generally considered an "anti-pattern" (because, according to React creators," it creates a second source of truth for your data, which usually leads to bugs"). However, the original version of the React docs stated, "it's not an anti-pattern if you make it clear that the prop is only seed data for the component's internally-controlled state." The latter is precisely our use case.

Save the files and test the running application.

In practice, it is more common to read the note data from a database or fetch it from an external API. In those cases, you should not perform the initialization in the constructor. Instead, you should update the state inside the componentDidMount method:

  1. Undo the changes you made to the constructor:
constructor(props) {
  super(props);
  this.state = {
    title: "",
    text: "",
  };
}
  1. Add the following method to UpsertNote component:
componentDidMount() {
const { state } = this.props.location;
  if (state) {
    const { id, title, text } = state;
    this.setState({
      id,
      title,
      text,
    });
  }
}

Save the file and visit the running app. It must work as before!

Note that componentDidMount is a special method declared in React.Component. This method is invoked immediately after the component is inserted into the DOM. React's documentation recommends using this method to load data from a database or instantiate a network request. This recommendation is made to make the app more performant.

The componentDidMount is a React Component's lifecycle method!

In React, every component has a lifecycle that it goes through!. By employing lifecycle methods (like componentDidMount), we can perform specific actions at different stages of each component's lifecycle. The lifecycle starts with a mounting phase, an updating phase, and finally, an unmounting phase.