I'm building a shopping cart page using Vuejs and Vuex. Each item in the cart should have a quantity counter to increase or decrease number of pieces ordered for this specific item. When I add products to the cart from the main products page then visit the cart page. I click on the counter and the product quantity is changed but the UI doesn't show this change. It only shows the change after I reload the page and after that it can show any new changes to only this specific counter, and I have to reload after adding every product just to make its counter show UI changes.
This is the cart Vue component simplified:
<template >
<tbody>
<tr v-for="product in cartProducts" :key="product.name">
<td class="quantity">
<i class="fa fa-minus" @click="decreaseQuantity(product)"></i>
<p>{{product.quantity}}</p>
<i class="fa fa-plus" @click="increaseQuantity(product)"></i>
</td>
</tr>
</tbody>
</template>
<script>
export default {
computed: {
cartProducts() {
return this.$store.state.cartProducts;
},
},
methods: {
increaseQuantity(drug) {
const existedDrug = this.cartProducts.find(d => d.id === drug.id);
existedDrug.quantity += 1;
this.$store.dispatch("setUserDataCart", this.cartProducts);
console.log(this.$store.state.cartProducts);
},
decreaseQuantity(drug) {
const existedDrug = this.cartProducts.find(d => d.id === drug.id);
existedDrug.quantity -= 1;
this.$store.dispatch("setUserDataCart", this.cartProducts);
console.log(this.$store.state.cartProducts);
},
},
};
</script>
And this is my vuex store:
import Vue from "vue";
import Vuex from "vuex";
import VuexPersist from "vuex-persist";
Vue.use(Vuex);
const vuexPersist = new VuexPersist({
key: "my-app",
storage: window.localStorage
});
const store = new Vuex.Store({
state: {
cartProducts: []
},
mutations: {
SET_USER_CART(state, data) {
state.cartProducts = data;
}
},
actions: {
setUserDataCart({ commit }, data) {
commit("SET_USER_CART", data);
}
},
plugins: [vuexPersist.plugin]
});
export default store;
I tried multiple approaches like using mapState or using the state as a getter but no luck.
Can anyone identify what am I doing wrong?