I'm having an issue when I select a sub-item from the select option tag, which incremental into my price is showing.
For example, my price: is 1, I select sub-item has price is 1 then which incremental 1 1 = 2, but when I select other items also has a price is 1 then which incremental 2 1 = 3.
How to prevent incremental on my price?
Sub-item: {name: 'name1', price: 1}
and {name: 'name2', price: 1}
My code:
const [price, setPrice] = useState(item.price)
useEffect(() => {
if (optionSelected === 'option') {
setPrice(item.price)
} else if (!isEmpty(optionSelected)) {
setPrice(price optionSelected.price)
}
}, [optionSelected])
Thanks to all of you!
CodePudding user response:
Your 2nd setPrice
should use the callback argument, since it updates price using its previous value.
(See https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)
setPrice((price)=>(price optionSelected.price))
CodePudding user response:
This is always adding:
setPrice(price optionSelected.price)
So since the previous price was the item price plus the sub-item price, the new price will be that previous total plus the new sub-item price.
Instead of adding to the existing total price, add to the item price to produce a new total:
setPrice(item.price optionSelected.price)