Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase transaction reads null at path even when there is data at that path

I understand that firebase transactions sometimes reads data as null but then the loop runs again until the value is obtained from server and committed. However I'm facing a unique situation where transaction reads null data and commits the value which I return in case of null. Please have a look at the attached code.

 deductTransaction.transaction((current_value) => {
       if (current_value != null) {
           return current_value - cost;
       }
       return 25;
   });

In the code above "deductTransaction" is the path of the data (number) which I want to update

The above code runs fine in some cases i.e the loop runs again in case null is read and sometimes it just runs once, reads the value as null even if there was some data at that path and then commits 25 thus destroying the original data

P.S: I'm close to pulling my hair out so any help would be highly appreciated

like image 482
Umer Mirza Avatar asked Oct 29 '25 17:10

Umer Mirza


1 Answers

When you run a transaction at a location the callback/handler is immediately invoked with the client's current guess of the value at that location. Most often this initial guess of the current value will be null.

Your handler needs to handle this situation. So: say that no data exists at the location and you want to deduct the cost, what would happen? Typically you'd either return -25 or you'd tell the transaction to abort.

Either way: the initial guess and new value will be sent to the database server, which then detects that the initial guess was wrong, and return the current value to the caller. The SDK then invokes your handler/callback again, with the (nope hopefully correct) best guess at the current value.

Also see:

  • Firebase realtime database transaction handler gets called twice most of the time (with a diagram of the above flow)
  • Firebase runTransaction not working - MutableData is null
  • Understanding conflict resolution in firebase
  • Why is the currentData in my Firebase transaction always nil?

Note: you can nowadays perform increment and decrement operations without a transaction by using the increment operator. This will significantly simply your code, and performs better as shown in How quickly can you atomically increment a value on the Firebase Realtime Database?.

For comparison: the increment operator assumes a current value of 0 if no value exists at the location.

like image 82
Frank van Puffelen Avatar answered Nov 01 '25 06:11

Frank van Puffelen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!