I have this cart state in which the initial value is an empty array [].
const [cart,setCart] = useState([]);
This is how one of my product object looks like,
{id: 1, name: 'Shoe pair', price: 40}
There is an add to cart button for each product. So when the add to cart button is clicked addToCart function is triggered,
const addToCart = (item) => {
let initialItem = {id: item.id, name: item.name, quantity: 1}
let existingItem = cart.filter(cartItem => item.id === cartItem.id);
if(existingItem.length > 0){
existingItem.quantity = existingItem.quantity + 1;
} else {
setCart(crr => [...crr, initialItem ]);
}
}
What does addToCart do? As you can see it is simple.First, it creates an object by setting the initial quantity to 1. If already the same product is present in the cart it updates the quantity in the cart product by 1 else the initialItem being added to the cart.
To monitor this occurrence I used useEffect hook,
useEffect(() => {
console.log(cart);
}, [cart]);
My problem is I can't see the cart in the console log when the quantity updates by 1 , But it shows when the initialItem is being pushed to the cart.
.quantityproperty.