Reputation: 3327
I have an react burger builder component, where you can add ingredients to a burger. This is the setup I have so far.
const INGREDIENT_PRICES = {
salad: 5,
cheese: 10,
meat: 20,
bacon: 10
}
class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30,
purchaseble: false
}
}
So for each item added, the state will update, as well as the price, which is defined in the top.
I have a handler to add ingredients to the burger like such:
addIngredientHandler = (type) => {
const oldCount = this.state.ingredients[type];
const updatedCount = oldCount +1;
const updatedIngredients = {
...this.state.ingredients
};
updatedIngredients[type] = updatedCount;
const priceAddition = INGREDIENT_PRICES[type];
const newPrice = this.state.totalPrice + priceAddition
this.setState({totalPrice: newPrice, ingredients: updatedIngredients})
this.updatePurchaseState();
}
this updates the ingredients in the state of the BurgerBuilder component. And then triggers the render method, to update the view of the burger on the page.
Moreso I have an updatePurchaseState, which is used to enable and disable the button, to submit a purchase.
Now does not update, whenever the this.updatePurchaseState
the method is called so I used the chrome dev tool to identify the problem.
Why doesn't the state update after the first function call?
Upvotes: 1
Views: 103
Reputation: 1234
setState
again.You need to use the callback
this.setState(
{totalPrice: newPrice, ingredients: updatedIngredients},
() => this.updatePurchaseState()
);
setState()
does not always immediately update the component. It may batch or defer the update until later. This makes readingthis.state
right after callingsetState()
a potential pitfall. Instead, usecomponentDidUpdate
or a setState callback (setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
Upvotes: 3