I'm trying to decrement or increment a cart in Vuex when I click, but the change doesn't reflect until I re-render the component or click "commit" again in the devtools for Vue.
What my store looks like:
- state
state: {
toggleSideBar: false,
cart: [],
},
- Action
action:{
incrementCart: ({ commit }, payload) => {
commit("INCREMENT_CART", payload);
},
addToCart: ({ commit, state }, payload) => {
commit("ADD_TO_CART", payload);
},
}
- mutation
mutation:{
INCREMENT_CART(state, payload) {
let index = state.cart.findIndex((x) => x.id === payload);
state.cart[index].amount += 1;
},
ADD_TO_CART(state, payload) {
let amount = 1;
if (state.cart.length === 0) {
payload.amount = amount;
return state.cart.push(payload);
} else {
if (state.cart.some((cart) => cart.id === payload.id)) {
let index = state.cart.findIndex((x) => x.id === payload.id);
state.cart[index].amount += amount;
} else {
payload.amount = amount;
state.cart.push(payload);
}
}
},
}
- then in my component
computed: {
cartData() {
return this.$store.state.cart;
console.log(this.$store.state.cart);
},
}
In which the value is then passed as props to individual cart