sinan
sinan

Reputation: 570

ComponentDidUpdate usage and Maximum update depth exceeded

I have a setting screen where I get number of info from user such as age, weight and gender and after this info I am calculating how much water user should drink per day.

I would like to calculate this amount automatically without any need of calculate button.

Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

My current code to calculate water amount

  //function to calculate how much water to drink
  waterCalculator = () => {
    //let weightPound = this.state.weight * 2.2046;
    let weightValue = this.state.weight;
    let ageValue = this.state.age;
    let waterAmount = null;
    if (ageValue < 30) {
      waterAmount = weightValue * 40;
    } else if (ageValue >= 30 || ageValue <= 55) {
      waterAmount = weightValue * 35;
    } else {
      waterAmount = weightValue * 30;
    }
    this.setState({ sliderValue: waterAmount });
  };

This how I want to automatically update my water amount

  //checking if age and weight and gender states are changed call the function
   componentDidUpdate(prevState) {
     if (
       this.state.age !== prevState.age &&
       this.state.weight !== prevState.weight &&
       this.state.gender !== prevState.gender
     ) {
       this.waterCalculator();
     }
   }

Upvotes: 2

Views: 9698

Answers (2)

nanobar
nanobar

Reputation: 66355

I would avoid componentDidUpdate entirely by doing it when weight, age, or gender changes i.e.

onChange = name = e => {
  this.setState({ [name]: e.target.value }, this.calcSliderValue);
}

calcSliderValue = () => {
  if (all_inputs_are_filled) {
    this.setState({ sliderValue: x });
  }
}

<yourGenderInput onChange={this.onChange('gender')} ... />
<yourAgeInput onChange={this.onChange('age')} ... />

Upvotes: 4

Isaac
Isaac

Reputation: 12874

componentDidUpdate(prevState) { // <===Error

}

The problem is with the first argument in componentDidUpdate is prevProps not prevState

To fix the problem

componentDidUpdate(prevProps, prevState) {
  ...
}

Simply place prevState into second argument

Upvotes: 5

Related Questions