Docs Menu
Docs Home
/ /
Atlas Device SDKs
/ / /

UUID - React Native SDK

On this page

  • Usage
  • Example

New in version realm@10.5.0.

UUID (Universal Unique Identifier) is a 16-byte unique value. UUID is bundled with the Realm package as part of BSON (Realm.BSON.UUID).

You can use UUID as an unique identifier for objects. UUID is indexable, and you can use it as a primary key.

class Profile extends Realm.Object {
static schema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}
class Profile extends Realm.Object<Profile> {
_id!: Realm.BSON.UUID;
name!: string;
static schema: ObjectSchema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}

To define a property as a UUID, set its type to "uuid" in your object model. Create a Realm object within a write transaction. To set any unique identifier properties of your object to a random value, call new UUID(). Alternatively, pass a string to new UUID() to set the unique identifier property to a specific value.

In the following CreateProfileInput example, we create a Profile Realm.Object with a uuid type for the _id field.

The CreateProfileInput component does the following:

  • Gets access to the opened realm instance by calling the useRealm() hook.

  • Creates a name state variable
    called "name" that represents the name of the profile.
  • Creates a createProfile method that performs a write transaction. Within
    that write transaction, we create a Profile object with the name value of the "name" state variable and an _id value of a new UUID object.
  • Renders a TextInput component that allows the user to enter a name for
    the profile. When the user presses the "Create Profile" button, the createProfile method is called and creates a Profile object.
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );

Back

Mixed

On this page