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" } } }
Active listener (the function triggers on data changes):
jsxfirebase.database().ref('application/user_1').on('value', snapshot => { if(snapshot.val()){ // Executes every time the anonymous user changes mail, name or picture } });
One time read (the function triggers only one time):
jsxlet snapshot = await firebase.database().ref('application/user_1').once('value'); if(snapshot.val()){ // Executes only one time }
Setting data with overwriting:
jsxfirebase.database().ref('application/user_1').set({ mail: "incognito@incognito.com", name: "Anonymous" });
Notice that user_1.picture
will be removed after executing this function.
Setting data without overwriting:
jsxfirebase.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
.
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:
jsxfirebase.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" } } }
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:
jsxfirebase.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.