[Vuex] Mutation that replaces object if ID already exists and pushes new object if it doesn't

I have a bunch of records stored as objects in an array in a Vuex module. I want to create a STORE_RECORD mutation that receives a record object with an id property. If a record with the same id already exists in the array the mutation should replace that record with the record object it received, otherwise the new record object should be added to the array.

Since this must be a very common pattern I imagine there is an established or recommended way of doing this. Can anyone give me some example code for such a mutation?

Thanks

Hi

One way of doing it would be something like this:

const index = this.items.findIndex(item => item.id == newItem.id)
if (index == -1) {
  this.items.push(newItem)
} else {
  this.items.splice(index, 1, newItem)
}
1 Like

Thanks very much. I had written something very similar (below) based on a SO post but wondered if there might be any better alternatives. Good to know I was on the right track :slight_smile:

function pushOrReplace(array, record) {
    const index = array.findIndex(item => item.id === record.id);
      if (index === -1) {
        array.push(record);
      } else {
        array[index] = record;
      }
    }

pushOrReplace(state.records, record);
1 Like

Your version is fine but one thing could be a problem. If the array is a vue reactive object will it not work to set the array[index]. That was why I used splice. See here https://vuejs.org/v2/guide/list.html#Caveats

1 Like

Thanks for pointing that out. I wasn’t aware of that limitation. Thanks again for your help.

1 Like