Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComponentDidUpdate SetState ReactJS Infinite loop

Even though there are many questions with the same subject line, I could not get an answer for my problem.

Problem

I have a select dropdown. On click of which, I call an Api which fetches some key values. I consider this set of key value input fields as a component. So each and every time onChange of my select drop-down, I have used lifecycle methods to handle API Calls. Also, I record these input key values and send back their state to parent component.

According to ReactJS lifecycle methods:

I use

componentDidMount To call the API for the first time after initial render. This works.

componentDidUpdate To call the API for subsequent API calls on select drop-down change. But here is the problem. When I try to update the state of input fields the program falls into an infinite loop and hence there are infinite API calls. I am pretty sure after debugging that the problem is with setState(), But I couldnt find the best way to handle states in componentDidUpdate method.

This link exactly replicates my problem but i want a standardized solution

Hope this is clear. Thanks for the help in advance!

like image 670
bks4line Avatar asked Mar 12 '23 22:03

bks4line


1 Answers

This is spelled out pretty clearly in the docs:

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

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.

like image 118
Madbreaks Avatar answered Mar 16 '23 06:03

Madbreaks