Sam
Sam

Reputation: 30288

How to generate UUIDs in JS or React?

In my React app, I want to do optimistic updates to create a responsive experience for my users.

Having said that I want to send a user entry to my backend with an ID that will be used so that there won't be a different Id for the user's entry next time he/she uses the app. For example, if the user enters a comment, I want to assign its ID with a real UUID and then send it to my API.

I understand JavaScript or React don't really have a built-in way to generate UUID/GUID values. I've seen many articles that produce randomized values that look like UUID/GUID's but they really are not and I don't want to use them as ID's for user entries.

How do I get real UUID/GUID values in my frontend? Do I call my backend API to get them? I can create an endpoint in my API that spits out 10 or 20 GUID's at a time and I can store them for future use in my frontend but this sounds a bit absurd.

I don't want to reinvent the wheel here as I'm not the first person to face this scenario. How do I get real UUID values on my frontend?

Upvotes: 35

Views: 149512

Answers (4)

mrconcerned
mrconcerned

Reputation: 1945

Can also generate them by using some simple regex.

function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

console.log(generateUUID());

Upvotes: 0

xyz_kunal
xyz_kunal

Reputation: 121

just use crypto.randomUUID()

available in most of the newer browser versions.

Upvotes: 12

markau
markau

Reputation: 922

You can use the uuid npm package. You probably want to use a v4 UUID. (Previous UUID versions use things like a timestamp or network card MAC address as seeds to the random generator).

Upvotes: 31

Dan Wilkerson
Dan Wilkerson

Reputation: 91

You're probably just fine generating them client-side - it takes many, many UUIDs before you even approach a 1 in a million rate of collision (citing the answer below).

This answer has several solutions to generating them client-side in a way that complies with RFC4122:

Create GUID / UUID in JavaScript?

Alternatively, you could generate temporary optimistic IDs and then replace them when you get a response from the server.

Upvotes: 4

Related Questions