dimanche 9 mai 2021

How can I prevent from adding duplicate on a list in React?

Hello all knowledgeable and talented SO members :)

I hope you can help me with this one too. I wish to do the following:

  1. on submit check if the item is already on the list
  2. if yes show an alert, and NOT add
  3. if NO add the item to the list After searching online, I came up with the following code
  const submitHandler = (e) => {
    e.preventDefault();
    const newScorer = e.target.value;
    const existingScorer = players.includes(newScorer);

    if (existingScorer) {
       console.log('already on list!');
    } else {
      const newPlayer = {id: nanoid(4), nummer: number};
      setPlayers([...players, newPlayer]);
      setNumber('');
    }
  };

The problem is that it does not work, adds even though "newScorer" is already on the list!?!

Thanks in advance

Regards Peter

Aucun commentaire:

Enregistrer un commentaire