Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda