3

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

Umer Mirza
  • 31
  • 1
  • Based on the tags, it seems you use this transaction in a Cloud Function. Could you add the **entire** code of the Cloud Function? – Renaud Tarnec Dec 22 '20 at 20:17

1 Answers1

1

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:


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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807