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