I'm trying to update the quantity of each item , i have tried my code but it didn't work correctly, but when i tried a solution found here: How to update item quantity in the shopping cart using React Redux , it worked thankfully . But i want to understand why my code didn't work (i'm using useContext not redux but normally that has nothing to do with the problem ) **Code that worked : ** :
cartItems: state.cartItems.map(item => item.id === payload.id
? {
...item,
qty: item.qty + 1,
}
: item
),
**My unfunctional code : **
if (productsInCard.find((x) => x.name === e.name)) {
let qu ; //to get the new quantity
const arr = [...productsInCard];
productsInCard.forEach((ele, index) => {
if (ele.name === e.name) {
qu = ele.quantity + 1;
console.log(ele.quantity + " this is the quantity before +1")
arr.splice(index, 1);
addCard(arr);
console.log("old item deleted" + JSON.stringify(arr))
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: qu,
},
]);
console.log(" item + quantity added : " + JSON.stringify(productsInCard));
}
});
const newArr = [...productsInCard]
productsInCard.forEach((ele, index)=>{
if(ele.name === e.name){
console.log(ele.quantity)
if (ele.quantity < qu)
newArr.splice(index, 1)
addCard(newArr);
}
})
} else {
addCard([
...productsInCard,
{
name: e.name,
price: e.price,
image: e.images[0],
quantity: 1,
},
]);
console.log("list with new item : " + productsInCard);
}
}