0

I have created a script that performs a request with firebase. Since I want to avoid multiple queries on a relation at the same time, I use the transaction function as seen in the code. First, I get the current status of the relation and check if it is present or not. This seems to work. The first time is const current = null and the function to add value to data2 will be executed.

And if I run the script the second time, then he goes into the next function successfully (doSecondFunction()). And unfortunately, no currentData returns to me here. I expect the value of the ref data2 that was added the first time. But as a result, I get null.

Is there a way to work in the transaction with the current state of the database?

const ref = firebase.database().ref('data2');
    ref.once('value', function(snapshot) {
        const current = snapshot.val();

                if(current == null){
                    console.log('FIRST');
                    addValToRefFunction();
                }else{
                    console.log('SECOND');
                    doSecondFunction(current, ref);
                }
            });

function doSecondFunction(current, ref){
                ref.transaction(function(currentData){
                    console.log(current); // result is the right value  
                    console.log(currentData); // result is null ?
                    if (currentData === current){
                        console.log('Check');
                        return;
            }         
}
Prags
  • 2,457
  • 2
  • 21
  • 38
labo28
  • 91
  • 1
  • 6

1 Answers1

0

There is no way control what the client sees as the current status of a node when starting a transaction. In my experience the first time the callback gets invoked, the value is almost always null, and the callback needs to handle that.

Also see my answer here for a description of the process: Firebase runTransaction not working - MutableData is null

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