[Vuejs]-Reactivity doesn't work using state in VueJS and Vuex

1👍

Vue. set is a tool that allows us to add a new property to an already reactive object and makes sure that this new property is ALSO reactive.

So, according to your problem, Vue.set will work well for you. Use it like this-

Vue.set(state.productsInBag, itemIndex, product)

Optional-

Also by looking at your fiddle’s code, you can make a common function in your helper file to find the product’s index like his-

export const findByIndex = (arr, matcher) => {
 return arr.findIndex(item => item.id === matcher)
}

And import this function in your js file like this-

import { findByIndex } from "YOUR_HELPER_FILE_PATH"

Now, the mutations can use like this-

DECREASE_PRODUCT(state, product) {     
  let itemIndex = findByIndex(state.productsInBag, product.id)
  if(itemIndex != -1) {
    product.quantity--
    Vue.set(state.productsInBag, itemIndex, product)
  }
},

INCREASE_PRODUCT(state, product) {    
  let itemIndex = findByIndex(state.productsInBag, product.id)
  if(itemIndex != -1) {
    product.quantity++
    Vue.set(state.productsInBag, itemIndex, product)
  }
}

A Little Tip-

Instead of making two mutation methods, a single mutation can be created which will accept the product_id and operation (increase or decrease) in an object, like this-

UPDATE_PRODUCT(state, payload) {
  // payload is an object which will have some data
  let itemIndex = findByIndex(state.productsInBag, payload.product_id)
  if(itemIndex != -1) {
    payload.operation == 'increase' ? product.quantity-- : product.quantity++;
    Vue.set(state.productsInBag, itemIndex, product)
  }
}

Leave a comment