Reputation: 2426
I am using AngularJS and FireBase in my app. When a user press a button I want to increase the price of the auctioning item by $0.01 and after it has been committed to the FireBase DB - deduct $1.00 from the user's balance. I use FireBase transaction() for that, but the value of the item is not updated in the FireBase DB:
$scope.auctionPriceRef = travelBidsFirebaseRef.child('auction/' + $scope.auction.id + '/price');
$scope.auctionPriceRef.transaction(function(currentValue) {
console.log("Current val + 0.01: " + (currentValue + 0.01));
return currentValue + 0.01;
}, function(error, committed, snapshot) {
if (error) {
console.error("Error increasing auction price: " + error);
}
if (committed) {
console.log("Successfully increased auction price to: " + snapshot.val());
$rootScope.authUser.balance -= 1.0;
}
});
This code executes without errors and I can see the following output at the console (the initial price of the item is 1.00):
Current val + 0.01: 1.01
Successfully increased auction price to: 1
The collback is executed, no error but the snapshot value is wrong. When I check in the Forge I can confirm that the value has not been updated there. Strange... There is another strange thing here: when I click the button several times very fast some transactions are actually being committed. Did anyone experienced similar behaviour or has an explanation to that? My code seems to be correct... or not?
Upvotes: 1
Views: 1090
Reputation: 2426
The problem was not in the transaction() itself but in the fact that I have bound the parent object of the 'price' - Auction to my local scope variable:
angularFire(travelBidsFirebaseRef + "/auction/" + $scope.auctionId, $scope, 'auction', {});
Right before the transaction to update 'price' is triggered, I update another property - 'endDate' of the bound Auction object:
$scope.auction.endDate = new Date(millis).toUTCString();
This line of code triggers the update of the whole Auction object, including 'price'. I expected that only the 'endDate' property will be updated.
This king of code creates racing condition where my 'price' update is overriden right after the commit and the collback returns not what I was expecting.
It's important to understand what exactly data is being syncronized with FireBase, and don't create multiple references to the same data - it may kick you in the ... when the app becomes more complicated.
Upvotes: 1