DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await