Most common functions in Firebase

Let's assume that we have a light database in Firebase containing an incognito user:

terminal
{
  "application" : {
    "user_1" : {
        "mail" : "anonymous@anonymous.com",
        "name" : "Incognito",
        "picture" : "anonymous.png"
    }
  }
}

Reading

Function .on()

Active listener (the function triggers on data changes):

jsx
firebase.database().ref('application/user_1').on('value', snapshot => {
    
    if(snapshot.val()){
        
        // Executes every time the anonymous user changes mail, name or picture
        
    }
    
});

Function .once()

One time read (the function triggers only one time):

jsx
let snapshot = await firebase.database().ref('application/user_1').once('value');

if(snapshot.val()){
    
    // Executes only one time
    
}

Writing

Function .set()

Setting data with overwriting:

jsx
firebase.database().ref('application/user_1').set({
    
    mail: "incognito@incognito.com",
    name: "Anonymous"
    
});

Notice that user_1.picture will be removed after executing this function.

Function .update()

Setting data without overwriting:

jsx
firebase.database().ref('application/user_1').update({
    
    mail: "incognito@incognito.com",
    name: "Anonymous"
    
});

Now user_1.mail and user_1.name will be updated and user_1.picture will be anonymous.png.

Function .push()

Pushing new data (for example, a new user):

Pushing data is useful to let Firebase to assing a key for you. For example, let's assume that a second anonymous user wanted to join ThE AnOnYmOuS PaRTy:

jsx
firebase.database().ref('application/').push({
    
    mail: "superincognito@superincognito.com",
    name: "MegaAnonymous",
    picture: "invisible.png"

});

Firebase creates a new object with a long and weird key:

terminal
{
  "application" : {
    "-M5Y49AOHizregfq5lEX": {
        "mail": "superincognito@superincognito.com",
        "name": "MegaAnonymous",
        "picture": "invisible.png"
    },
    "user_1" : {
        "mail" : "anonymous@anonymous.com",
        "name" : "Incognito",
        "picture" : "anonymous.png"
    }
  }
}

Function .transaction()

Now let's assume that we create a new stats object:

terminal
{
  "application" : {
    "-M5Y49AOHizregfq5lEX": {
        "mail": "superincognito@superincognito.com",
        "name": "MegaAnonymous",
        "picture": "invisible.png"
    },
    "user_1" : {
        "mail" : "anonymous@anonymous.com",
        "name" : "Incognito",
        "picture" : "anonymous.png"
    }
  },
  "stats": {
    "onlineUsers": 0
  }
}

If both users access to stats.onlineUsers at the same time to increase its value, we may have issues with the total value. To prevent them, Firebase has a transaction method:

jsx
firebase.database().ref('stats/onlineUsers').transaction(value => value + 1);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.