I've been working on an e-commerce website and when i click on an item to get it into the car, i've created a function to push the element into a Car array.
const getItem=(id) =>{
const product=products.find(item =>
item.id === id)
return product;
}
const addToCart=(id)=>{
let tempProducts=[...products]
const index=tempProducts.indexOf(getItem(id))
const product=tempProducts[index];
product.inCart=true;
product.count=1;
const price=product.price;
product.total=price;
setCart([...cart,product]);
setProductos(tempProducts);
console.log(cart)
}
The problem that i got is when i clicked to the first element to go into the Cart array it pushes an empty value, but when i clicked the second item, it brings me the previous array that i clicked.
I don't know what happens with the index but if you know about it, please tell me