So if anyone else runs into this question/issue, here is what I did to resolve it:
-
Check to see if the user’s current Realm is not the same as the Realm you would like them to be in.
if (!currentRealmInstance.syncSession.url.startsWith(desiredRealmURL))
-
If not, logged the user into the new Realm server. We use JWT, so this involved creating the credentials then logging in.
const user = await Realm.Sync.User.login(ServerURL, credentials);
-
Opened a new instance of Realm with this user.
const newRealm = new Realm(realmConfig);
. We also are keeping a reference of the old Realm.
-
Copy the data over into the new Realm. We used an array of the Realm schema objects we wanted to copy over. In this code example it is just the User data.
const promises = ['User'].map(obj =>
const data = oldRealm.objects(schema);
if (data.length) {
data.forEach(el => {
newRealm.write(() => {
newRealm.create(schema, el, 'modified');
});
});
}
);
- After all the data has copied over we saved the Realm instance.
Promise.all(promises)
.then(async () => {
return dispatch({
type: 'set_realm_connection',
payload: newRealm,
});
})
- Since we are using Redux, we refreshed our reducers with the copied data.
Here’s the data on the frontend that we used to open the app or wait until the current Realm URL equals the desired Realm URL.
checkRealmInstance = setInterval(async () => {
const {realm} = this.props;
if (!Realm.Sync.User.current) {
clearInterval(this.checkExist); // Don't perform checks if user isn't logged into Realm
} else if (realm.syncSession.url && !realm.syncSession.url.startsWith(RealmURL)) {
await this.props.getUserData(); // Loads data from current (old) Realm
this.props.updateSpinnerVisibility(true, 'Updating Profile');
this.props.copyDataToNewRealm();
} else if (realm.syncSession.url && realm.syncSession.url.startsWith(RealmURL)) {
clearInterval(this.checkExist);
this.props.updateSpinnerVisibility(false);
await this.props.getUserData(); // Retrieves new data and places in Redux
this.props.navigation.navigate('App');
} else {
console.log('.'); // Waiting for initial Realm to load
}
}, 100);