Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda