Answer the question
In order to leave comments, you need to log in
Why does the class method not pick up the necessary data in states if you call it from the constructor?
I have a component with a constructor that looks like this:
class Day extends Component {
constructor(props) {
super(props);
this.state = {
calories: 0,
fat: 0,
protein: 0,
carbs: 0,
};
this.caloriesCalculate();
}
caloriesCalculate() {
var fat = 0;
var protein = 0;
var carbs = 0;
var calories = 0;
const { dataArray, mealPlan, date } = this.props;
const { products } = dataArray;
var timestamp = date._i/1000;
Object.keys(mealPlan[timestamp]).map(function(type) {
var product = products[mealPlan[timestamp][type]];
fat += product.fat/1000;
protein += product.protein/1000;
carbs += product.carb/1000;
calories += product.calories/1000;
});
var nutritions = {
calories: calories,
fat: fat,
protein: protein,
carbs: carbs,
}
this.setState(nutritions);
}
onClick={() => this.caloriesCalculate()}
<li className='day-calories'><b>Calories:</b> {calories}, <b>Fat:</b> {fat}g, <b>Protein:</b> {protein}g, <b>Carbs:</b> {carbs}g</li>
Answer the question
In order to leave comments, you need to log in
In calculateCalories, instead of calling setState, you should return the computed state:
class Day extends React.Component {
state = this.calculateCalories();
calculateCalories() {
/* ... */
return {
calories,
fat,
protein,
carbs,
};
}
handleClick = () => {
this.setState(this.calculateCalories());
};
render() {
...
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question