1

i have problem here, when i click into one element 2 times it will add 2 time into my array, i dont know how to add unique element into array, can u guys help me? Thank you guys

 const handleClick = (
    id: number,
    name: string | null,
    avatar: string | null
  ) => {
    setListChoose((prevState: any) =>
      [...prevState].concat({ id, name, avatar })
    );
  };

enter image description here

4
  • 2
    Use an obejct instead of an array. Use the id as the key. Commented Jun 18, 2022 at 8:06
  • Is your id supposed to be unique? Commented Jun 18, 2022 at 8:08
  • yes, id is unique Commented Jun 18, 2022 at 8:09
  • @super can i guide me? Commented Jun 18, 2022 at 8:12

1 Answer 1

1

You can check that whether that contact exists in array or not. If not then append in list else don't.

const handleClick = (
    id: number,
    name: string | null,
    avatar: string | null
  ) => {
    let list = Array.from(listChoose); //assuming that list name is listChoose.
    if(list.find(l => l.id === id) === undefined){
       setListChoose((prevState: any) =>
          [...prevState].concat({ id, name, avatar })
       );
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.