After I authenticate and sync my react native app with my database cluster using MongoDB Realm Sync, I want to open my app completely offline. How can I do that ? It works fine when I open it online. But, when I open it offline, it does not return anything , neither it gives any error.
Below is my code:
Hi,
I had similar issue regarding using offline only with the iOS SDK. And I found the following solution. Not quite sure what you should use in the React Native SDK, but maybe this can help you anyways.
First time I login in the app I’m using the Realm.OpenAsync() function (after successfully logon), to get data from the server. Once the data is received the user is automatically stored behind the scenes in the keychain by the SDK. When I open the app next time I won’t do a Realm.OpenAsync(). I first look at the Realm.App instance and try to get the user from that by doing app.currentUser. If a user is available then I can use that user to initialize Realm.
See below:
let configuration = AppConfiguration(
baseURL: // Custom base URL
transport: nil, // Custom RLMNetworkTransportProtocol
localAppName: "AppName",
localAppVersion: "1.0",
defaultRequestTimeoutMS: 30000
)
let app = App(id: "someId", configuration: configuration)
if let user = app.currentUser {
var config = user.configuration(partitionValue: "SHARED")
config.objectTypes = kSyncedObjectTypes
do {
let realm = try Realm.init(configuration: config, queue: .main)
}
} else {
let creds = Credentials.jwt(token: "someToken"
app.login(credentials: creds) { result in
switch result {
case .success(let user):
var config = user.configuration(partitionValue: "SHARED")
config.objectTypes = kSyncedObjectTypes
Realm.asyncOpen(configuration: config, callbackQueue: .main, callback: completion)
}
}
}
The important thing is that you always need the user to create the configuration and to open the Realm db.
So Realm.asyncOpen for the initial load/first time login and from that point you will always need to use Realm.init() from the locally stored user.
I haven’t tried in the React Native SDK, but I think it would something like this:
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"
}
};
}
Hi @Lukasz_Stachurski i’m facing the same problem with RN, i already have my app.currentUser but it’s not enought to complete the connection with Realm MongoDB offline, do you have any working offline example that you can share with us ?