React props no being set after function execution

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.

Here is the debugger at first, where the salad-ingredient is added one to the state, as it should, and then updating the state

Here is the debugger, when diving into the updatePurchaseState function, but without the updated state

Why doesn't the state update after the first function call?

Upvotes: 1

Views: 103

Answers (1)

dovidweisz
dovidweisz

Reputation: 1234

React is waiting to see if you call setState again.

You need to use the callback

this.setState(
    {totalPrice: newPrice, ingredients: updatedIngredients}, 
    () => this.updatePurchaseState()
);

From the react docs:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate 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

Related Questions