Search code examples
javascriptfirebase-realtime-databasetransactions

How to deal with null value in realtime database transaction?


I would like to have a counter that we can increment or decrement using transaction. I would like not to initialize the counter to 0, insteads it doesn't exist at start. So I would write the increment transaction as below

ref.transaction(function(counterValue){
    if (counterValue == null) return 1
    else return (counterValue +1)
},function(error,committed,snapshot){
   if (error){//fail
   }else if (!committed){//aborted
   }else{//successfull
   }
})

But I'm not sure if the transaction will run correctly since the null value of counterValue could mean no existing node but also when local cache is empty. Could anyone please advise me what I should do?


Solution

  • the null value of counterValue could mean no existing node but also when local cache is empty

    If the existing value is reported as null because the local cache doesn't contain a current value, the new value you return doesn't really matter as your handler will be rerun anyway.

    So your handler looks fine to me, although I typically shorten it to:

    return (counterValue || 0) + 1