my cart items is not showing in the cart(which is in state using pinia) after adding them using an action from a button in the shop page
my code:
store.js(using pinia)
import { defineStore } from "pinia";
import Products from "../db.json";
export const useCounterStore = defineStore("counter", {
state: () => ({
cart: [],
}),
actions: {
addToCart(id) {
this.cart.push(id)
console.log("test passed!")
}
}
});
shop.vue
<template>
<div >
<h1>shop</h1>
<div v-for="item in Products" :key="item.id">
{{ item.name }} {{ item.price }}$
<button @click="storeCounter.addToCart(item.id)">Add to Cart</button>
</div>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
import Products from "../db.json"
const storeCounter = useCounterStore()
</script>
cart.vue
<template>
<div >
<h1>cart</h1>
<div v-for="item in storeCounter.cart" :key="item.id">{{ item.name }} {{ item.price }}</div>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
import Products from "../db.json"
const storeCounter = useCounterStore()
</script>
why it is not working for me? i assume i did everything right...
CodePudding user response:
shop.vue
is only pushing the id number into the store's cart
array
<button @click="storeCounter.addToCart(item.id)">
cart.vue
is attempting to display the cart
array as if contains full product objects and not just the ids
<div v-for="item in storeCounter.cart" :key="item.id">
{{ item.name }} {{ item.price }}
</div>
This can be easily fixed by changing shop.vue
to add the full item
instead of just item.id
<button @click="storeCounter.addToCart(item)">