Problem:
What my code wants to achieve is — when I click the increment button, the increment value quantityCount
is used to multiply the object sellingPrice
. But what I get is — the initial value of the quantityCount
multiplies the sellingPrice
, but when I increase the count quantityCount
it doesn’t dynamically multiply the sellingPrice
object as shown in the console.
Would appreciate your help on this, thanks.
const [productName, setProductName] = useState("");
const [sellingPrice, setSellingPrice] = useState(0);
const [quantityCount, setQuantityCount] = useState(0); //useState Variable handling my Increment and Decrement
const [newItems, setNewItems] = useState([])
const enterProductName = (e) =>{
setProductName(e.target.value);
}
const enterSellingPrice = (e) =>{
let sellingPricePerEach = e.target.value
setSellingPrice(sellingPricePerEach * quantityCount);
console.log(sellingPricePerEach * quantityCount);
}
let handleSaveItem = () => {
const newItemData = {productName, sellingPrice,quantityCount};
setNewItems([...newItems, newItemData]);
console.log(newItemData);
}
let incrementQuantity = () =>{
setQuantityCount(quantityCount+ 1);
//console.log(quantityCount+ 1);
}
let decrementQuantity = () =>{
setQuantityCount(quantityCount- 1);
// console.log(quantityCount- 1);
}
//JSX
<div>Items</div>
{newItems.map((items)=>{
const {productName,sellingPrice, quantityCount} = items;
return(
<>
<div>
<div><div>{productName}</div>
<div>{sellingPrice}</div>
</div>
<div><FontAwesomeIcon icon={faTrashCan} /></div>
</div>
</>
);
})}
//JSX
<div>Quantity</div>
<div>
<FontAwesomeIcon icon={faPlus} onClick={incrementQuantity}/>
{quantityCount}
<FontAwesomeIcon icon={faMinus} onClick={decrementQuantity}/>
</div>
Solution:
Jacob already answered the question, but here is the answer to extend his comment — use useEffect
The reason it doesn’t work from your original logic is the state stays the same (in this case, quantityCount
) until the next render. That is why when you clicked “Increment”, the quantityCount
being used is still the old one rather than the updated one you’ve been expecting.
In this case, we need a way to “watch” the quantityCount
, so when we can update the sellingPrice
as quantityCount
changes.
This can be achieved by adding the following lines in your component —
useEffect(()=>{
if (quantityCount === 0) return // safeguard invalid value
setSellingPrice(quantityCount * sellingPrice)
}, [quantityCount])
(Unrelated — useReducer
is another technique for increment and decrement a state, but it a bit overkill for the simple state management in this component)
Example code https://codesandbox.io/s/wild-butterfly-9vmp2x?file=/src/App.tsx