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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With