i am trying to build a shop and i try to add items to the cart but for some reason the cart length is wrong as i am trying to be able to add items to the cart without having duplicates in terms of items names. so when i add the same item twice it basically shows only 1 item in the cart if though i have 2.
i tried changing the the addtocart function to recognize items by there id as my items have these properties: id, name, price and quantity. i am trying to count the number of items in the cart by using foreach loop. because when i tries using the javascript array.length function it did not worked. so i am trying now with foreach loop. my code is like this:
shop.vue:
<template>
<div>
<h1>Shop</h1>
Items in cart: {{ cartnum }}
<div v-for="item in Products" :key="item.id">
{{ item.name }} {{ item.price }}$
<button @click="storeCounter.addToCart(item)">Add to Cart</button>
</div>
</div>
</template>
<script setup>
import { useCounterStore } from "../stores/counter";
import { computed } from "vue";
import Products from "../db.json";
const storeCounter = useCounterStore();
const cartnum = computed(() => storeCounter.cartnum);
</script>
cart.vue:
<template>
<div class="cart">
<h1>Cart</h1>
<div class="cartitems" v-for="item in storeCounter.cart" :key="item.id">
{{ item.name }} {{ item.price }}$ {{ item.quantity }}
<button @click="storeCounter.removeFromCart(item)">X</button>
</div>
<h4>total items: {{ cartnum }}</h4>
<h4>Total Price: {{ cartSum }}</h4>
</div>
</template>
<script setup>
import { useCounterStore } from "../stores/counter";
import { computed } from "vue";
const storeCounter = useCounterStore();
const cartSum = computed(() => {
let total = 0;
storeCounter.cart.forEach((item) => {
total += item.price * item.quantity;
});
return total;
});
const cartnum = computed(() => storeCounter.cartnum);
</script>
pinia file:
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => ({
cart: [],
}),
actions: {
addToCart(item) {
let cartItemIndex = this.cart.findIndex((x) => x.id === item.id);
if (cartItemIndex >= 0) {
item.quantity++;
} else {
this.cart.push(item);
}
},
removeFromCart(id) {
let cartItemIndex = this.cart.findIndex((x) => x === id);
if (cartItemIndex >= 0) {
this.cart.splice(cartItemIndex, 1);
console.log("Removed from cart");
}
},
},
getters: {
cartnum() {
let total = 0;
this.cart.forEach((item) => {
total += item.quantity;
});
return total;
},
},
});
how do i fix that? thanks in advance!