Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add unique object into array reactjs

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 })
       );
    }
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading