Video Course

Getting Started with React: Lesson 12 of 14

Lifecycle Methods

Up Next

PropTypes

Autoplaying in 7 seconds!

Cancel

Every React component has three main points in its life: mounting, updating, and unmounting. We can hook into these points through methods React exposes on the component class. This way we can run some code after a component mounts or before it is destroyed, for example.

To demonstrate this, we will change our application to first pull down the data from the API. This will tell us what zip codes we have data on. We will allow a user to select a zip code from a select menu and then update the data shown based on the selected zip. Let's get to it!

First, let's add the weather data to the state of our App component.

this.state = {
  weatherData: [],
  zipcode: '',
  city: {},
  dates: [],
  selectedDate: null
};

Next we will pass the list of zip codes to our ZipForm component.

render() {
  const { weatherData, dates, city, selectedDate } = this.state;
  const zips = weatherData.map(w => w.id);

  return (
    <div className="app">
      <ZipForm zips={zips} onSubmit={this.onFormSubmit} />
      <WeatherList days={dates} onDayClicked={this.onDayClicked} />
      {selectedDate !== null && <CurrentDay day={dates[selectedDate]} city={city} />}
    </div>
  );
}

Then, in the render of the ZipForm, we will output a select list with these zip codes.

render() {
  return (
    <div className="zip-form">
      <form>
        <label htmlFor="zipcode">Zip Code</label>
        <select onChange={this.submitZipCode}>
          <option value="">Select a zip</option>
          {this.props.zips.map(zip =>
            <option key={zip} value={zip}>{zip}</option>
          )}
        </select>
      </form>
    </div>
  );
}

We can also remove inputUpdated and change submitZipCode to use the value of the event target.

submitZipCode(e) {
  const { onSubmit } = this.props;

  onSubmit(e.target.value);
}

Lastly, we just need to update onFormSubmit back in our App component to pull the weather data from the data we have already stored locally in state.

onFormSubmit(zip) {
  const zipcode = zip * 1;
  const { weatherData } = this.state;
  const data = weatherData.find(wd => wd.id === zipcode);
  const { city, list: dates } = data;

  this.setState({ zipcode, city, dates, selectedDate: null });
}

If we view the page, we can't select anything. That's because we haven't gotten the data yet. There are many lifecycle methods that React exposes. You can read about them all in the React documentation. We are going to utilize one of the more popular ones, componentDidMount. As the method explains, this is called once the component mounts to the DOM. It's a good place to send off AJAX requests to setup our initial state.

Create a new method on the App component called componentDidMount and make it look like this.

componentDidMount() {
  get('http://localhost:3000/weather')
    .then(({ data: weatherData }) => {
      this.setState({ weatherData });
    });
}

Since this method will automatically get called by React once the component is mounted. This means we don't have to call it anywhere. It goes out and grabs the data and sets it in our component. It's that simple.

There are many more to check out. Read the React docs on lifecycle methods for more information.

One last thing to discuss. We can enforce the types of the props we expect to get passed to our components using prop types!

Alex Sears

2 posts

Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?