Search code examples
vuejs2statevuexmutationvuex-modules

Vuex mutation inside array of objects after backend update saves


I have an array of objects. When my api executes the update method and saves, I'm am broadcasting an event through laravel-echo-server and attempting to mutate state with the update object. I'm trying for real-time updates. Everything but the actual mutation is going according to plan. Here is the beginning of it:

updateExample (state, example) {
  state.examples.map(e => {
    if (e.id === example.id) {
      // entirely replace the old object with the new
    }
    return false
  })
},

What is an ideal way to do this? I could also pop the old object out of the array and push a new one, but that seems wonky.


Solution

  • Nevermind, figured it out:

    updateExample (state, example) {
      let index = state.examples.findIndex(e => e.id === example.id)
      if (index !== -1) {
        state.examples[index] = new Example(example)
        return
      }
      state.examples.push(new Example(example))
    }
    

    Thanks for looking at it!