Navigation

Sync Data

Overview

Realm Sync lets you share data across devices, between Realm clients and a synced MongoDB Atlas cluster and is a solution for offline-first app development. To learn more about Realm Sync, see Sync Overview.

Prerequisites

Before you can access a synced realm from the client, you must:

Open a Synced Realm

To open a synced realm for a given partition value, initialize a Realm by passing a configuration object to “realm.open”. The config object should have a sync field that is an object with the authenticated user, and the partition value as fields:

const config = {
   schema: [MySchema],
   sync: {
     user: user,
     partitionValue: partitionValue,
   },
 };
try {
   let realm = await Realm.open(config);
} catch (error) {
   console.error(error);
}

The partition value specifies which subset of your data to sync. This is typically a user ID, project ID, store ID, or some other category identifier in your app that has particular relevance to the current user.

Sync Data

The syntax to read, write, and watch for changes on a synced realm is identical to the syntax for non-synced realms. While you work with local data, Realm efficiently integrates, uploads, and downloads changesets.

The following code reads a collection of Task objects, watches that collection for changes, then writes a new Task to the realm:

// open a realm with the config object with a synced field
let realm = await Realm.open(config);

const syncTasks = realm.objects("Task");

// Watch for changes. No special syntax required for synced realms.
realm.addListener("change", () => {
  console.log("sync tasks - ", syncTasks);
});
realm.write(() => {
  realm.deleteAll();
});
// Write to the realm. No special syntax required for synced realms.
realm.write(() => {
  realm.create("Task", {
    name: "buy groceries",
    description: "go to store and buy milk, eggs and bread",
  });
});

// remove listeners and close the synced realm when done observing
realm.removeAllListeners();
realm.close();

Summary

  • Open a synced realm by creating a config object with a sync sub-object that has a partition value.
  • The syntax for reading from, writing to, or watching objects on a synced realm is the same as the syntax for a non-synced realm