Question

I'd like to assign an incremental number to users while they click on #div1 or #div2. Multiple user from different devices can get their subsequent number without problem with the following codes:

$("#div1").click(function(event) {
    doBtn();
}

$("#div2").click(function(event) {
    doBtn();
}

function doBtn() {
    counterRef.transaction( function(currentData) {
      if (currentData === null) {
        return 1; 
      } else {
        // increase the counterRef by 1
        return currentData + 1;
      }
    }, function(error, committed, snapshot) {
      if (error) {
      } else if (!committed) {
      } else {
        // upon counterRef updated successfully, add a child {user: "userId", counter: xxxx} to ListRef
        // (xxxx is the increased counter number)
        ListRef.push({
            user: "userId",
            counter: snapshot.val()
        });
      }
    } );
}

counterRef.on('value', function(snapshot) {
    console.log( "Current number is " + snapshot.val() );
}

ListRef.on('child_added', function(snapshot) {
    console.log( "Your number is " + snapshot.val().counter );
}

However, if the user click the same button (or clicking #div1 and #div2 alternatively) rapidly, they will get the following results:

Current number is 1 Current number is 2 Current number is 3 Current number is 4 Current number is 5 Current number is 6 Current number is 7 Current number is 8

Your number is 1 Your number is 3 Your number is 3 Your number is 4 Your number is 5 Your number is 6 Your number is 8 Your number is 8

It seems that the snapshot value in function(error, committed, snapshot) cannot get the concurrent value from counterRef while being increased.

Am I using the .transaction() wrong?

Please help.

Était-ce utile?

La solution

Unfortunately, based on @Kato's reproduction, I think this is expected behavior based on our current implementation.

Basically, if you do multiple transactions rapidly (or while you're offline), we'll end up batching them together and performing them as a single batch, and the final snapshot each one gets will be the final snapshot after all of them ran.

I understand this may not always be ideal. We'll look into whether we could perhaps change this behavior in the future.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top