Jafrul Hossain
Jafrul Hossain

Reputation: 9

How can I stop componentDidUpdate from creating an an infinite loop

I am a newbie in react. In my program every time I set the ajax request in componentDidUpdate() and set the new state then it creates a infinite loop. And one more thing " is that the right way that make ajax call in componentDidmount() and componentDidUpdate()?"

Here is my Handler function

componentDidUpdate() {
  this.getUnitsHandler();
}

componentDidMount() {
  this.getUnitsHandler();
}

getUnitsHandler = () => {
  Axios.get('http://localhost:4000/getUnit').then(response => {
    this.setState({
      units: response.data
    })

  }).catch(err => {
    console.log(err);
  })
}

What should be the logic here to stop the infinite loop?

Upvotes: 0

Views: 1742

Answers (4)

Shashank Pandey
Shashank Pandey

Reputation: 31

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition something like this,

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

or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead.

If you are working only with state, you can capture the previous state from componentDidUpdate callback.

Upvotes: 0

J. Ryd
J. Ryd

Reputation: 44

You should never do setState in componentDidUpdate, since setState triggers that exact method again. What exactly do you want to achieve? A single API call when the component has been mounted? If so, use it inside componentDidMount instead.

Upvotes: 0

bajran
bajran

Reputation: 1503

It is good to write the ajax call in componentDidMount() method, because it execute after rendering of dom, it executes only one time when your component loads , but if you try to update the component then, your componentDidUpdate will execute every time when you update your dom. so the best way to do ajax call is componentDidMount method. from react doc componentDidMount

Upvotes: 0

Clarity
Clarity

Reputation: 10873

Usually you need to check if your props change and only then make an update:

componentDidUpdate(prevProps) {
  if (prevProps[someKey] !== this.props[someKey]) {
    this.getUnitsHandler();
  }
}

However, in this case you're not using any instance variables to make the api call, so you don't need to use componentDidUpdate at all.

Adding the api call to componentDidMount will make the requests after the component is mounted, which looking at the code, should be enough for your purposes.

Useful links:

Data fetching in React

React component lifecycle

Upvotes: 2

Related Questions