Necessary imports eg useState, useDispatch
function ItemCard(props) {
const [count, setCount] = useState(0);
const dispatch = useDispatch();
Here I am trying to use a button which triggers this function and increases count, but when I console.log
it, it prints the older value. When I send the count to dispatch, the older value also gets passed in.
const addCount = () => {
setCount((prevCount) => prevCount + 1);
console.log(count);
dispatch(
updateCart(
"ADD_TO_CART",
{ id: props.id, name: props.name, price: props.price },
count
)
);
};
const decreaseCount = () => {
if (count > 0) {
setCount((prevCount) => prevCount - 1);
dispatch(
updateCart(
"REMOVE_FROM_CART",
{ id: props.id, name: props.name, price: props.price },
count
)
);
}
};
return (
<div className="card">
<div className="image">
<img src={props.img} alt="cookie" />
</div>
<div className="title">
<h2>{props.name}</h2>
<h2>Rs.{props.price}</h2>
</div>
<p className="detail">{props.detail}</p>
<div className="buttons">
<button onClick={addCount} id="add-to-cart">
+
</button>
<span>{count}</span>
<button onClick={decreaseCount} id="add-to-cart">
-
</button>
</div>
</div>
);
}
export default ItemCard;