[Vuejs]-How can I add new values to an array object of state using Vuex?

1👍

This bit looks wrong:

for (let key in data) {
    this.$set(data[key].find(e => e.doctor_id === item.doctor_id && e.hospital_id === item.hospital_id), 'schedule', this.dataSchedule.schedule)
}

From the sample data you posted this will only find something for (at most) one value of key. For the other values of key the find will return undefined and the $set will fail.

Try this:

for (const key in data) {
  const entry = data[key].find(e => e.doctor_id === item.doctor_id && e.hospital_id === item.hospital_id)

  console.log(`key is ${key}:`, entry)

  if (entry) {
    this.$set(entry, 'schedule', this.dataSchedule.schedule)
  }
}

Of course it is also possible that none of the entries will match. The console logging I’ve included should help you to identify that scenario too.

I should add that it is usually regarded as best practice to mutate store state within a store mutation rather than directly inside a component.

Leave a comment