I'm stuck trying to update the state of a simple cart but can't get it to work. Basically when I click to update state, it seems not getting the initial state, only on the second round. So how to make it work correctly?
const { product } = props;
const [subTotal, setSubTotal] = useState(0);
const [itemQty, setItemQty] = useState(0);
const handleCart = (event) => {
const id = product.itemId;
const price = product.price;
setSubTotal(subTotal Number(price));
setItemQty(itemQty 1);
}
return (
<div>
<Image
src={product.url}
alt={product.title}
className="product__image"
/>
<div className="product__title">{product.title}</div>
<div className="product__price">{`$ ${product.price}`}</div>
<Button
className="product__qty-btn-p btn btn-primary"
type="button"
data-id="increase"
onClick={() => handleCart()}
id="basic-addon2"
>
Add
</Button>
</div>
)
CodePudding user response:
That happen because state is asynchronous.
You can use useEffect
to console.log
that state:
import React.{useState,useEffect} from "react"
const { product } = props;
const [subTotal, setSubTotal] = useState(0);
const [itemQty, setItemQty] = useState(0);
useEffect(() => console.log(subTotal,itemQty),[subTotal,itemQty])
const handleCart = (event) => {
const id = event.product.itemId;
const price = event.product.price;
setSubTotal(prev => {prev Number(price)});
setItemQty(prev => {prev 1});
}