react-hooks
react-hooks copied to clipboard
Dupicate ids
Generating ids with array length results in duplicate ids.
Steps to recreate the issue: 1- Load the application. At this point we have an item with id = 1, id=2 and id = 3 2- Delete the first item with id = 1 3- Add a new item , this item also gets id of 3 4- Now there are two users with id = 3. 5- Deleting either of them deletes both the rows.
How to solve that?
@phota @masthanvalismd
const addUser = user => {
user.id = !(users.length) ? 1 : users.at(-1).id + 1;
setUsers([ ...users, user ])
}
If the users array length is empty, set ID to 1. Otherwise, get last user ID in the array and increment it by 1. In the real world scenario you would have these entries in the database which means every entry would have unique ID.