Docs Menu

Docs HomeDevelop ApplicationsAtlas Device SDK

CRUD - Create - React Native SDK

On this page

  • Create an Object with a To-One Relationship
  • Create an Object with a To-Many Relationship
  • Create an Embedded Object
  • Create an Asymmetric Object

To add a new Realm object to a realm instance, use realm.create() inside of a write transaction. If the schema includes the object type and the object conforms to the schema, then Realm stores the object.

The example for creating an object uses the following schema:

To create a new object:

  1. Access a realm instance using the useRealm() hook.

  2. Create handleAddPerson(), which creates a new Person object based on the TextInput value.

  3. Add an onPress event on the submit button that calls handleAddPerson().

1const CreatePersonInput = () => {
2 const [name, setName] = useState('');
3 const realm = useRealm();
4
5 const handleAddPerson = () => {
6 realm.write(() => {
7 realm.create('Person', {_id: PERSON_ID, name: name, age: 25});
8 });
9 };
10
11 return (
12 <>
13 <TextInput value={name} onChangeText={setName} />
14 <Button
15 onPress={() => handleAddPerson()}
16 title='Add Person'
17 />
18 </>
19 );
20};

In a one-to-one relationship, an object is related to at most one other object of a particular type. To learn more about one-to-one relationships, refer to to Relationships & Embedded Objects.

The example for creating an object with a to-one relationship uses the following schema to indicate that a Pet Owner may only own one Pet:

To create an object with a to-one relationship to another object:

  1. Query the realm for a pre-existing Pet object. Assign the result to newPet.

  2. Create a new PetOwner object and pass newPet to the pet property.

  3. Wrap your write transaction in a handleAddPetOwner() function, which creates a new PetOwner object with an associated Pet.

  4. Add an onPress event on the submit button that calls handleAddPetOwner().

1const CreatePetOwnerInput = () => {
2 const [ownerName, setOwnerName] = useState('');
3 const realm = useRealm();
4 const newPet = useObject(Pet, PET_ID);
5
6 const handleAddPetOwner = () => {
7 // Create a new Pet Owner object, pass new Pet object in pet field
8 realm.write(() => {
9 realm.create('PetOwner', {
10 _id: PETOWNER_ID,
11 name: ownerName,
12 age: 25,
13 pet: newPet,
14 });
15 });
16 };
17
18 return (
19 <>
20 <TextInput
21 onChangeText={setOwnerName}
22 value={ownerName}
23
24 />
25 <Button
26 onPress={() => handleAddPetOwner()}
27 title='Add New Pet Owner'
28 />
29 </>
30 );
31};

In a one-to-many relationship, an object may be related to multiple objects of a particular type. To learn more about one-to-many relationships, refer to to Relationships & Embedded Objects.

The example for creating an object with a to-many relationship uses the following schema to indicate that a Company may employ multiple Employees:

To create an object with a to-many relationship to another object:

  1. Query the realm for all pre-existing Employee objects using useQuery().

  2. Create a new Company object and pass the results of your previous query to the employees property.

  3. Wrap your write transaction in a handleAddCompany() function, which creates a new Company object with an associated list of Employees.

  4. Add an onPress event on the submit button that calls handleAddCompany().

1const CreateNewCompanyInput = () => {
2 const employees = useQuery(Employee);
3 const [companyName, setCompanyName] = useState('');
4 const realm = useRealm();
5
6 // Create a new Company and connect our list of Employees to it
7 const handleCreateCompany = () => {
8 realm.write(() => {
9 realm.create('Company', {
10 _id: COMPANY_ID,
11 name: companyName,
12 employees: employees,
13 });
14 });
15 };
16
17 return (
18 <>
19 <TextInput
20 onChangeText={setCompanyName}
21 value={companyName}
22
23 />
24 <Button
25 onPress={() => handleCreateCompany()}
26 title='Add New Company'
27 />
28 </>
29 );
30};

An embedded object is an object that exists as data nested inside of a parent object; it cannot exist as an independent Realm object. To learn more about embedded objects, refer to to Relationships & Embedded Objects.

The example for representing an embedded object uses the following schema that allows you to embed a single Address into a new Contact object:

To create an embedded object, assign an instance of the embedded object to a parent object's property.

The following CreateContact example creates a new Contact object with an embedded Address object.

The CreateContact component does the following:

  1. Creates React state variables that represent the contact's name and address details.

  2. Gets access to an open realm instance by calling the useRealm() hook within the component.

  3. Creates a component method submitContact() that performs a write transaction to create a new Address embedded object and Contact parent object based on the TextInput values for the contact's name and address.

  4. Adds an onPress event on the "Submit Contact" button that calls submitContact().

1const CreateContact = () => {
2 const [name, setContactName] = useState('');
3 const [street, setStreet] = useState('');
4 const [city, setCity] = useState('');
5 const [country, setCountry] = useState('');
6 const [postalCode, setPostalCode] = useState('');
7 const realm = useRealm();
8
9 const submitContact = () => {
10 // Create a Contact within a write transaction
11 realm.write(() => {
12 // Create an embedded Address object
13 const address = {
14 street,
15 city,
16 country,
17 postalCode,
18 };
19
20 realm.create('Contact', {
21 _id: new Realm.BSON.ObjectID(),
22 name,
23 // Embed the address in the Contact object
24 address,
25 });
26 });
27 };
28 return (
29 <View>
30 <TextInput value={name} onChangeText={text => setContactName(text)} />
31 <TextInput value={street} onChangeText={text => setStreet(text)} />
32 <TextInput value={city} onChangeText={text => setCity(text)} />
33 <TextInput value={country} onChangeText={text => setCountry(text)} />
34 <TextInput
35 value={postalCode}
36 onChangeText={text => setPostalCode(text)}
37 />
38 <Button
39 title='Submit Contact'
40 onPress={submitContact}
41 />
42 </View>
43 );
44};

An asymmetric object allows you to sync a collection unidirectionally from your decive to your Atlas database, if you are using Flexible Sync. To learn more about asymmetric objects, refer to to Stream Data to Atlas.

The example for creating an asymmetric object uses the following schema that defines a Weather Sensor object for sending weather-related data one-way from your device to your Atlas database:

You can create an asymmetric object inside a write transaction using realm.create(). When creating an asymmetric object, Realm.create() returns undefined rather than the object itself.

const App = () => {
// Getting access to our opened realm instance
const realm = useRealm();
const handleAddSensor = () => {
realm.write(() => {
realm.create('WeatherSensor', {
_id: weatherSensorPrimaryKey,
deviceId: 'WX1278UIT',
temperatureInFahrenheit: 66.7,
barometricPressureInHg: 29.65,
windSpeedInMph: 2,
});
});
};
return (
<Button
title='Add A New Sensor'
onPress={() => handleAddSensor()}
/>
);
};
←  CRUD - React Native SDKCRUD - Read - React Native SDK →