I am learning and practicing react for sometime. But came upon a weird problem. I'm making a small e-commerce application (step by step with tutorial).
const addToCart = (id) => {
let tempProduct = storeProduct;
const index = tempProduct.indexOf(getItem(id));
const product = tempProduct[index];
product.inCart=true;
product.count = 1;
product.total = product.price;
setCart([...cart,product]);
setStoreProduct(tempProduct);
console.log(cart)
};
storeProduct is an array of objects that are the products in my application.
Called this function onClick on a button. It takes the element by id and makes some changed in the data. Then should add that element in the cart which is an array. But on the first click, the cart is empty. On the second click, the first clicked element gets into cart and so on. What is the problem here?