Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Setting unique id with array.length+1 results in same ids

When clicking on a button i call a function to set a unique ID of an object and then push the object inside an array:

 const addItems = (item) => {
    item.uniqueId = addedItems.length + 1;
    addedItems.push(item);
  };

It works as intended if i add the items slowly, but if i press multiple times a second on the button the unique id will be the same (and a wrong one, not the one in line: for example if i have 2 items in the array with unique id of 1 and 2 and then press fast on the button 3 times, those 3 objects will have a unique id of 5, all 3 of them). What is wrong here?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Assuming it is state you must always update it in immutable way:

setAddedItems(ps=>[...ps,{...item,uniqueId:ps.length+1}])

And indeed this way as mentioned in other answer if you remove items, then add new ones, the ids may repeat; but if items aren't removed, then this approach is ok.

You can also check uuid if you want to remove items too.

about 4 years ago · Juan Pablo Isaza Report

0

Your code have many minuses, I recommend you use nanoid. If you will remove item from your useState, some ids could be same. Better use an index for this if you would not change your state (remove items)

It will look like:

const addItems = (item) => {
  setAddedItems((addedItems) => [
    ...addedItems, { ...item, uniqueId: nanoid() }
  ])
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!