Navigation

Quick Start - React Native SDK

This page contains information to quickly get Realm Database integrated into your app.

Important

If you will be using Sync and other backend features of Realm in your app, see Quick Start with Sync - React Native SDK.

At the top of your source files where you want to use MongoDB Realm, add the following line to import the SDK.

import Realm from "realm";

Your application's object model defines the data that you can store within Realm Database.

To define a Realm object type, create a schema object that specifies the type's name and properties. The type name must be unique among object types in a realm. For details on how to define specific properties, see Define Object Properties.

Example

The following code shows how to define an object model for a Task object. In this example:

  • The primaryKey is the _id of type int (Another common type used for primary keys is ObjectId).
  • The name field is required. The
  • The status is optional, denoted by the question mark immediately after the data type.
const TaskSchema = {
name: "Task",
properties: {
_id: "int",
name: "string",
status: "string?",
},
primaryKey: "_id",
};

To open a realm, pass a Realm.Configuration object to either Realm.open() or new Realm().

const realm = await Realm.open({
path: "myrealm",
schema: [TaskSchema],
});

Once you have opened a realm, you can create objects in it. All writes must occur within a Write transaction.

Example

In the following example, an application developer creates two tasks. One task with a name of "go grocery shopping" and another with the name of "go exercise". Both tasks have a status of "Open".

// Add a couple of Tasks in a single, atomic transaction
let task1, task2;
realm.write(() => {
task1 = realm.create("Task", {
_id: 1,
name: "go grocery shopping",
status: "Open",
});
task2 = realm.create("Task", {
_id: 2,
name: "go exercise",
status: "Open",
});
console.log(`created two tasks: ${task1.name} & ${task2.name}`);
});
// use task1 and task2

The following code demonstrates how to:

  • Query for all instances of the "Task" object type.
  • Filter the query to retrieve only the tasks that are "Open".
  • Sort the tasks by the name in an ascending order.
// query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");
console.log(`The lists of tasks are: ${tasks.map((task) => task.name)}`);
// filter for all tasks with a status of "Open"
const openTasks = tasks.filtered("status = 'Open'");
console.log(
`The lists of open tasks are: ${openTasks.map( (openTask) => openTask.name )}`
);
// Sort tasks by name in ascending order
const tasksByName = tasks.sorted("name");
console.log(
`The lists of tasks in alphabetical order are: ${tasksByName.map( (taskByName) => taskByName.name )}`
);

As with writes, any changes to a Realm object must occur within a Write transaction block. To modify an object, you update the object properties:

Example

In the following example, an application developer updates task1 from the Create Realm Objects example above. The developer begins progress on the "go grocery shopping task" and sets task1 to "InProgress".

realm.write(() => {
task1.status = "InProgress";
});

You can delete an object by calling the realm.delete() method within a write transaction block:

Example

In the following example, an application developer deletes task1 from the Create Realm Objects example above.

realm.write(() => {
// Delete the task from the realm.
realm.delete(task1);
// Discard the reference.
task1 = null;
});

You can watch a realm, collection, or object for changes by registering event handlers with the Realm.addListener() Object.addListener() Collection.addListener() methods.

Example

In the following example, an application developer watches for changes to the Task collection.

// Define the collection notification listener
function listener(tasks, changes) {
// Update UI in response to deleted objects
changes.deletions.forEach((index) => {
// Deleted objects cannot be accessed directly,
// but we can update a UI list, etc. knowing the index.
console.log(`A task was deleted at the ${index} index`);
});
// Update UI in response to inserted objects
changes.insertions.forEach((index) => {
let insertedTasks = tasks[index];
console.log(
`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`
);
// ...
});
// Update UI in response to modified objects
// `newModifications` contains object indexes from after they were modified
changes.newModifications.forEach((index) => {
let modifiedTask = tasks[index];
console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`);
// ...
});
}
// Observe collection notifications.
tasks.addListener(listener);

Call the realm.close() method when done with a realm instance to avoid memory leaks.

// Remember to close the realm
realm.close();

The following code is a fully runnable example that includes all of the concepts on this page.

import Realm from "realm";
const TaskSchema = {
name: "Task",
properties: {
_id: "int",
name: "string",
status: "string?",
},
primaryKey: "_id",
};
async function quickStart() {
const realm = await Realm.open({
path: "myrealm",
schema: [TaskSchema],
});
// Add a couple of Tasks in a single, atomic transaction
let task1, task2;
realm.write(() => {
task1 = realm.create("Task", {
_id: 1,
name: "go grocery shopping",
status: "Open",
});
task2 = realm.create("Task", {
_id: 2,
name: "go exercise",
status: "Open",
});
console.log(`created two tasks: ${task1.name} & ${task2.name}`);
});
// use task1 and task2
// query realm for all instances of the "Task" type.
const tasks = realm.objects("Task");
console.log(`The lists of tasks are: ${tasks.map((task) => task.name)}`);
// filter for all tasks with a status of "Open"
const openTasks = tasks.filtered("status = 'Open'");
console.log(
`The lists of open tasks are: ${openTasks.map( (openTask) => openTask.name )}`
);
// Sort tasks by name in ascending order
const tasksByName = tasks.sorted("name");
console.log(
`The lists of tasks in alphabetical order are: ${tasksByName.map( (taskByName) => taskByName.name )}`
);
// Define the collection notification listener
function listener(tasks, changes) {
// Update UI in response to deleted objects
changes.deletions.forEach((index) => {
// Deleted objects cannot be accessed directly,
// but we can update a UI list, etc. knowing the index.
console.log(`A task was deleted at the ${index} index`);
});
// Update UI in response to inserted objects
changes.insertions.forEach((index) => {
let insertedTasks = tasks[index];
console.log(
`insertedTasks: ${JSON.stringify(insertedTasks, null, 2)}`
);
// ...
});
// Update UI in response to modified objects
// `newModifications` contains object indexes from after they were modified
changes.newModifications.forEach((index) => {
let modifiedTask = tasks[index];
console.log(`modifiedTask: ${JSON.stringify(modifiedTask, null, 2)}`);
// ...
});
}
// Observe collection notifications.
tasks.addListener(listener);
realm.write(() => {
task1.status = "InProgress";
});
realm.write(() => {
// Delete the task from the realm.
realm.delete(task1);
// Discard the reference.
task1 = null;
});
// Remember to close the realm
realm.close();
}
quickStart().catch((error) => {
console.log(`An error occurred: ${error}`);
});

Running the above code should output something like the following:

created two tasks: go grocery shopping & go exercise
The lists of tasks are: go grocery shopping,go exercise
The lists of open tasks are: go grocery shopping,go exercise
The lists of tasks in alphabetical order are: go exercise,go grocery shopping
modifiedTask: {
"_id": 1,
"name": "go grocery shopping",
"status": "InProgress"
}
A task was deleted at the 0 index
Give Feedback