DEV Community

miku86
miku86

Posted on

Diary - 2018.09.29

Read the Docs

I'm currently doing many small projects, today I'm working on a TV series finder. The user can input something and the React App outputs some data from an API.

The app worked, but there was an infinite loop, because componentDidMount() fetched some data and updated the state, so it started again...

componentDidUpdate = async () => {
  const series = await getAllSeries(this.props.searchWord);
  this.setState({ series });
};
Enter fullscreen mode Exit fullscreen mode

I searched for some time, but couldn't find a good solution.

So I headed over to the React Docs and there it was:

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop.

So I changed my code to:

componentDidUpdate = async (prevProps) => {
  if (this.props.searchWord !== prevProps.searchWord) {
    const series = await getAllSeries(this.props.searchWord);
    this.setState({ series });
  }
};
Enter fullscreen mode Exit fullscreen mode

and learned something new: read the docs.

Top comments (0)