react-nativerealm-js

How to prevent multi beginTransactions in Realmjs?


I create a function to handle transaction, then I call it to multi places. I got crash when another transaction not yet complete when I open new transaction.

Here my code:

const RealmMakeTransaction = async (action) => {
    try {
        realm.GetInstance().beginTransaction();
        let response = await action();
        realm.GetInstance().commitTransaction();

        return response;

    } catch (e) {

        realm.GetInstance().cancelTransaction();
    }
};

Solution

  • You can easily check if realm is already in transaction or not before calling beginTransaction() by calling realm.GetInstance().isInTransaction

    Your code will look like :

    const RealmMakeTransaction = async (action) => {
    
       //use single instance
       let realm = realm.GetInstance();
    
        try {
            if( realm.isInTransaction)
              realm.cancelTransaction();
    
            realm.beginTransaction();
            let response = await action();
            realm.commitTransaction();
            return response;
    
        } catch (e) {
    
            realm.cancelTransaction();
            realm.close();
        }
    };