[Vue warn]: Duplicate keys detected: x. This may cause an update error. How to prevent adding item which has already been added via method

Viewed 111

I have a v-autocomplete that loops a list of users. I then add them to a new list via a btn. How to I stop and alert that a user has already been added by comparing the dup key?

<v-autocomplete
    v-model="event.user"
    :items="usersData"
    label="Seach speaker list"
    :search-input.sync="searchUser"
    return-object
    item-value="id"
    item-text="name"
></v-autocomplete>

My method to addSpeaker is:

addSpeaker() {
    const newSpeaker = {
        id: this.event.user.uid,
        name: this.event.user.name,
    }
    this.speakers.push(newSpeaker)
    this.event.user = ''
},
removeSpeaker(id) {
    this.speakers = this.speakers.filter(speaker => speaker.id !== id)
}

Is there a check I can do here to prevent a user being added if it already has been?

2 Answers

Check if the user exists by using id. If the user exists then show an error, else add the user:

addSpeaker () {
  const newSpeaker = {
    id: this.event.user.uid,
    name: this.event.user.name,
  }

  let doesUserExists = false;

  for (let i = 0; i < this.speakers.length; i++) {
    if (this.speakers[i].id === newSpeaker.id) {
      // Show an error that the user does already exists

      doesUserExists = true;

      break;
    }
  }

  if (!doesUserExists) {
    this.speakers.push(newSpeaker);
  }

  this.event.user = ''
},

or by using for each loop:

...

this.speakers.forEach(function(speaker) {
  if (this.speakers[i].id === newSpeaker.id) {
    // Show an error that the user does already exists

    doesUserExists = true;

    return;
  }
});

...

you can use findIndex

addSpeaker() {
  const newSpeaker = {
    id: this.event.user.uid,
    name: this.event.user.name
  };
  const check = this.speakers.findIndex(x => x.name == this.event.user.name) === -1;
  check && this.speakers.push(newSpeaker);
  this.event.user = "";
}
Related