Home > Software design >  Setting unique id with array.length 1 results in same ids
Setting unique id with array.length 1 results in same ids

Time:05-30

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?

CodePudding user response:

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.

CodePudding user response:

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() }
  ])
}

CodePudding user response:

Use the setAddedItems to cause a render everytime you add an item to the state

 const addItems = (item) => {
    // this could cause issue if you also have remove item as pointed out 
    item.uniqueId = addedItems.length   1; // should use nanoid or uuid instead
    addedItems.push(item);
    setAddedItems([...addedItems])
  };

You should also probably do this in an immutable way as the other answers have it to avoid bugs.

  • Related