Firebase transaction api call current data is null

You need to follow this pattern:

var pinRef = firebase.database().ref('vm-pin-generator');
pinRef.transaction(function(oldPin) {
    // Check if the result is NOT NULL:
    if (oldPin != null) {
        return localPinIncrementor(oldPin);
    } else {
        // Return a value that is totally different 
        // from what is saved on the server at this address:
        return 0;
    }
}, function(error, committed, snapshot) {
    if (error) {
        console.log("error in transaction");
    } else if (!committed) {
        console.log("transaction not committed");
    } else {
        console.log("Transaction Committed");
    }
}, true);

Firebase usually returns a null value while retrieving a key for the first time but while saving it checks if the new value is similar to older value or not. If not, firebase will run the whole process again, and this time the correct value is returned by the server.

Adding a null check and returning a totally unexpected value (0 in this case) will make firebase run the cycle again.


Transactions work in the manner of Amazon's SimpleDB or a sharded cluster of databases. That is to say, they are "eventually consistent" rather than guaranteed consistent.

So when you are using transactions, the processing function may get called more than once with a local value (in some cases null if it's never been retrieved) and then again with the synced value (whatever is on the server).

Example:

pathRef.transaction(function(curValue) {

    // this part is eventually consistent and may be called several times

}, function(error, committed, ss) {

    // this part is guaranteed consistent and will match the final value set

});

This is really the mindset with which you must approach transaction anyways. You should always expect multiple calls, since the first transaction may collide with another change and be rejected. You can't use a transaction's processing method to fetch the server value (although you could read it out of the success callback).

Preventing the locally triggered event

When the transaction happens, a local event is triggered before it reaches the server for latency compensation. If the transaction fails, then the local event will be reverted (a change or remove event is triggered).

You can use the applyLocally property on transactions to override this behavior, which makes the local results slower but ensures that only the server value is triggered locally.

pathRef.transaction(function(curValue) {

    // this is still called multiple times

}, function(error, committed, ss) {

    // this part is guaranteed consistent and will match the final value set

}, 
    // by providing a third argument of `true`, no local event
    // is generated with the locally cached value.
true);