0
votes

I am trying to overwrite an object inside an array called device inside my store. the mutation saveState receives a device, if it doesn't exist in device array it would push the object , but if it is already existing it will just replace it with the received device. I tried searching for a solution for almost a day and I can’t the problem with my code.

store.device.js

export const state = () => ({
  device: []
})

export const mutations = {
  saveState(state, device) {
    var index = state.device.findIndex(dev => dev.id == device.id)
    index === -1 ? state.device.push(device) : (state.device[index] = device)
  }
}

export const getters = {
  getStateById: state => id => {
    return state.device.find(dev => dev.id === id)
  }
}

1

1 Answers

0
votes

The issue you are having is that Vue cannot detect state changes when you directly try to set an array index like you are doing with state.device[index] = device.

For this they provide Vue.set which allows you to update an array at a certain index. It is used like this:

//Vue.set(array, indexOfItem, newValue)
index === -1 ? state.device.push(device) : Vue.set(state.device, index, device);

You can read about it in the docs here