0

I have an app that allows users click buttons and create their own pizza. I am having a a problem with the price calculation.

const [pizzaSize, setPizzaSize] = useState(null);
  
  const [price, setPrice] = useState(0);
  const [startPrice, setStartPrice] = useState(0);
  const [toppingPrice, setToppingPrice] = useState(0)
  const changePizza = (e) => {
    setPizzaSize(e.target.name);
    setStartPrice(parseInt(e.target.value))
    setPrice(startPrice + toppingPrice )
  };

The user will click on the size of the pizza, which will change the startPrice (because bigger pizzas = more money) but won't change the price of toppings. Thus the total price is calculated with startPrice + toppingPrice
This function will fire everytime the user changes the size of the pizza.

<button
            type="button"
            value="10"
            name="Medium"
            onClick={(event) => {changePizza(event)
            
            }}
          >
            Medium
          </button>
          <button
            type="button"
            value="12"
            name="Large"
            onClick={(event) => {changePizza(event)
            }}
          >
            Large
          </button>

The issue I am having, is that the price seems to be showing the value of the previous button that was clicked. If you click once it will show 0, and if you click again it will show you the value of the button you had clicked before. Ex. Medium is 10, but when you click large => medium it will display 12.
I've looked through my code for a logic error but haven't found it. A full codesandbox is available here link. A second pair of eyes is very appreciated.

imstupidpleasehelp
  • 1,618
  • 2
  • 16
  • 36
  • 1
    `setPrice(startPrice + toppingPrice )` uses the value of `startPrice` from the *current* render cycle, not the value just enqueued by `setStartPrice(parseInt(e.target.value))` for the *next* render cycle. You can `setPrice(parseInt(e.target.value) + toppingPrice )` or use an effect to (re)compute `price` when `startPrice` updates. A more correct solution would be to ***not*** store `price` in state at all since it can be derived from the other two state values. – Drew Reese Dec 09 '20 at 07:18
  • So what would be the best way to store price? P.S. Nice to see you again, Drew! – imstupidpleasehelp Dec 09 '20 at 07:22
  • 1
    Hello again. If you *need* to store `price` then I suggest using an `useEffect` hook to update after `startPrice` or `toppingPrice` update, but like I said, this value is easily derived from your actual state. [Identify the Minimal State](https://reactjs.org/docs/thinking-in-react.html#step-3-identify-the-minimal-but-complete-representation-of-ui-state) -> "*3. Can you compute it based on any other state or props in your component? If so, it isn’t state.*" – Drew Reese Dec 09 '20 at 07:25

0 Answers0