DEV Community

Rafael Lima
Rafael Lima

Posted on

1

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay