Realm.open vs new Realm

早过忘川 提交于 2019-12-04 10:44:37

Is there any specific usecase you have in mind ? Otherwise within react native i havent had to use Realm.open so far. They way i've seen most people approach the architecture is to have a file named realm.js where the schemas are defined and a new Realm is exported like so

class ShoppingCartItem extends Realm.Object{}
ShoppingCartItem.schema = {
    name: 'ShoppingCartItem',
    primaryKey: 'ordernumber',
    properties: {
        ordernumber: 'string',
        quantity: 'int',
        unitPrice: 'double'
    }
}

export default new Realm({schema: [User, LastViewedProduct, ShoppingCartItem]});

and then have another file called realmTasks.js where you import that realm object and define actions on it. If you need the realm object in the local state to register changes you can define a callback and give it the realm reference as an argument such as

export function addShoppingCartItem(ordernumber, quantity, unitPrice, callback){
    realm.write(() => {
        realm.create('ShoppingCartItem', {
            ordernumber: ordernumber,
            quantity: quantity,
            unitPrice: unitPrice
        });
    })
    return callback(realm);
}

I'm not sure if this completely answers your question or is useful to you at all but i hope this gives you a hint :)

The answer from docs can completely cover your question. So using sync approach (const realm = new Realm()) is more simple and appropriate for exporting realm as a module, but it's still preferable to get promise Realm.open() and handle realm instance when schema migration and sync from remote server are completed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!