In React Native, where are you supposed to put the migration code or code to delete the realm database (ignoring migration) and for it to only run once?
I tried deleting the Realm database each time I am back on the Login screen. When I try to login, it is supposed to save the user info into Realm and then the app proceeds as normal. However this is not the case, it seems because Realm database was deleted, it has no where to save it. I would have thought that once I login, by saving the user info into Realm, it would initialize Realm and then save the user in Realm.
In debug mode, it seems even by deleting the Realm database, everything functions normally. Debug mode is a lot slower, so is there a timing issue somewhere?
Is there a method to initialize Realm?
This is what I did to get the migration to work.
I have realm.js located in /src where I keep all my react files. When I need to use my realm I import realm from 'path/to/realm.js';
In realm.js I have my old schema and my new schema.
import Realm from 'realm';
const schema = {
name: 'mySchema',
properties: {
name: 'string',
}
};
const schemaV1 = {
name: 'mySchema',
properties: {
name: 'string',
otherName: 'string',
}
};
Note they have the same name. Then at the bottom of my realm.js where I used to have export default new Realm({schema: [schema]});
I now have this:
export default new Realm({
schema: [schemaV1],
schemaVersion: 1,
migration: (oldRealm, newRealm) => {
// only apply this change if upgrading to schemaVersion 1
if (oldRealm.schemaVersion < 1) {
const oldObjects = oldRealm.objects('schema');
const newObjects = newRealm.objects('schema');
// loop through all objects and set the name property in the new schema
for (let i = 0; i < oldObjects.length; i++) {
newObjects[i].otherName = 'otherName';
}
}
},
});
If you don't need to migrate the data, you could just open the Realm with the new schema version and new schema and it should also work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With