DEV Community

Rafael Lima
Rafael Lima

Posted on

Creating users ID

Fix duplicated user IDs when adding a new one right before delete the last user.

❌Wasn't working like this

const id = Number(data.users.length + 1)

It happens that when you delete a user before the last, and create a new user, the new user gets the same id as the last. Making two users to have the same ID.

✔So i made it like this:

let id = 1
    const lastMember = data.users[data.users.length - 1]

    if (lastUser) {
        id = lastUser.id + 1
    }

Of course that is far from the best way to create unique user IDs, since we have node uniqid and other node packages. But it was made to be simple, just to get used with the language as i get better in logic and solve problems without an out of the box solution.

Top comments (0)