firebase-database Firebase Realtime Database Transactions A distributed counter


Imagine many users all running a web application that is trying to increment a counter in the database. Each user must read the current count, add one and write out the updated value. To make sure no one reads the counter while someone else is is adding one we use a transaction:

  if (value === null) {
    // the counter doesn't exist yet, start at one
    return 1;
  } else if (typeof value === 'number') {
    // increment - the normal case
    return value + 1;
  } else {
    // we can't increment non-numeric values
    console.log('The counter has a non-numeric value: ' + value)
    // letting the callback return undefined cancels the transaction