How can I use local copy of MongoDB Synced Realm database while completely offline?

Viewed 1037

I am using MongoDB Realm Sync on my React Native app. When I start my app online and later disconnect internet, my realm works fine. I can see my data and also I can write data which syncs with server when I go back online. But when I start my app completely offline, my app does not show any data. From what I understand, realm is suppose to read local database and return data even when the app starts from complete offline. Isn't it ? How can I access my data when I start my app offline ? Below is my code I've used to sync with server.

const config = {
      schema: [sessionSchema],
      sync: {
        user,
        partitionValue: 'Test',
      },
    };

try {
      Realm.open(config)
        .then((openedRealm) => {
          if (canceled) {
            openedRealm.close();
            return;
          }
          realmRef.current = openedRealm;
          const syncSessions = openedRealm.objects('session');

         openedRealm.addListener('change', () => {
            setSessions([...syncSessions]);
         });
        setSessions([...syncSessions]);
     }
  } catch (e) {
      console.log('ERROR', e);
    }
2 Answers
const OpenRealmBehaviorConfiguration = {
    type: "openImmediately",
}

const configuration = {
    schema: [UserSchema],
    sync: {
        user: app.currentUser,
        partitionValue: "user_1",
        // Add this two lines below
        newRealmFileBehavior: OpenRealmBehaviorConfiguration,
        existingRealmFileBehavior: OpenRealmBehaviorConfiguration,
    }
}

I found an answer for similar question here: https://developer.mongodb.com/community/forums/t/open-synced-local-database-when-completely-offline/11169/2 You can do something like:

async function getRealm() {
    const app = new Realm.App("your-app-id");
    if (app.currentUser) {
        // A user had already logged in - open the Realm synchronously
        return new Realm(getConfig(app.currentUser));
    }

    // We don't have a user - login a user and open the realm async
    const user = await app.logIn(Realm.Credentials.anonymous());
    return await Realm.open(getConfig(user));
}

function getConfig(user) {
    return {
        sync: {
            user,
            partitionValue: "my-partition"
        }
    };
}
Related