Firebase transaction api call current data is null

后端 未结 3 741
时光说笑
时光说笑 2020-12-01 12:10

When I use transaction() to update a location, data at that location is returning null even though the location having some da

3条回答
  •  -上瘾入骨i
    2020-12-01 13:09

    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.

提交回复
热议问题