When I use transaction()
to update a location, data at that location is returning null even though the location having some da
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.