I’m building a shopping cart and i encountered a problem decrementing products from the array.
this cart takes in a product, if a product already exist, increment its amount.
for decrementing if the item amount is ===1, add to cart.
This is my Add to cart function
addToCart(product:Product){
const ls = JSON.parse(localStorage.getItem('cartList') || '[]') as Product[] | null;
let productAlreadyInCart = false;
// Check if the product is already in the cart
for (let item of this.cartItemList) {
if (item.name === product.name) {
// If the product is already in the cart, increment its amount and price
item.amount ++
item.price = product.price * item.amount;
productAlreadyInCart = true;
localStorage.setItem('cartList', JSON.stringify(ls))
console.log(this.total,'item amount incremented')
break; // No need to continue looping once found
// console.log(this.total);
}
}
// If the product is not in the cart, add it
if(!productAlreadyInCart) {
// get list of produts in local storage and append
const newData = this.cartItemList.push({ ...product, amount: 1 });
localStorage.setItem('cartList', JSON.stringify(newData))
console.log('item added successfully')
}
// Update total
this.getTotal();
console.log(this.total, 'new item');
}
and i decrement, remove it from the array, otherwise just decrement the amount
now the incrementing works, Increment
incrementQuantity(product:Product){
console.log('item amount decremented', product)
// confirm if item exist
let item = this.cartItemList.find(item => item.name === product.name)
if(item){
item.amount +=1
item.price += product.price
}
this.getTotal();
}
my issue now is the decrementing
.
to understand the issue better i will create a use case, however you can skip and just look at the code snippets in my solution attempts
decrement
(Use case)
we wont touch on the incrementing, again, it works
for the decrement however, imagine we have a vase in our cart at $100,
product:Product[] =[{
name: 'vase',
price: 100,
description:'ceramic',
image: '../assets/vase.png',
BlackFridaySale: true,
amount: 0 //when we add an item the amount is set to 1
}]
when we increment to 3 vases, the price updates to 300$, however when i decrement, instead of remove 100 dollars which is the price of one, it removes the whole $300 and sets the price to 0
decremnetQuantity(product: Product){
for (let i = 0; i < this.cartItemList.length; i++) {
const item = this.cartItemList[i];
if (item.name === product.name) {
if (item.amount === 1) {
this.total -= item.price;
this.cartItemList.splice(i, 1);
} else {
item.amount--;
item.price -= product.price;
}
// this.updateCart();
this.getTotal();
break;
}
}
}
it seems i am somehow editing the same instance of my items in the array and i don’t know where its coming from.
i tried a for loop in the decrement logic, I’ll also put the rest of the important snippets so i don’t leave any gray area.
I’d appreciate some insight