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.