i have a question i've make this code to update my local storage, so everything work but when i update my local storage to add quantities, for exemple if i have already 2 couch and i add 2 more couch in my local storage the result is 22
So i think it miss some "parseInt" in my code but i don't realy know where so please that will be greatfull if you can help me i don't really know what to do
btnCart.addEventListener("click", (event)=>{
event.preventDefault();
function addToCart() {
let color = colorChoice.value;
console.log(color);
let name = productName;
console.log(name);
let price = productPrice;
console.log(price);
let quantity = productQuantity.value;
console.log(quantity);
const productToAdd = {
id : id,
name : name,
price : price,
color: color,
quantity: quantity
};
const currentCart = JSON.parse(localStorage.getItem(cartName)) ?? [];
const itemIndex = currentCart.findIndex((item) =>
item.id === productToAdd.id && item.color === productToAdd.color
);
if (itemIndex !== -1) {
currentCart[itemIndex].quantity += productToAdd.quantity;
}
else {
currentCart.push(productToAdd);
}
localStorage.setItem(cartName, JSON.stringify(currentCart));
}
addToCart();
})
LocalStorage return strings, so you can't do:
currentCart[itemIndex].quantity += productToAdd.quantity;
You need to parse the localStorage value eg:
const qty = parseInt(currentCart[itemIndex].quantity);
currentCart[itemIndex].quantity = qty + productToAdd.quantity;