How to set a listener on Firebase value event?

11,793

Solution 1

In order to make this question helpful for other people looking into same problem, here's an extended example from the question with missing functions and variables defined:

// some HTML element on the page
var postElement = document.getElementById("postElement");

// here I will assume that this function simply 
// updates the contents of the element with a value
var updateStarCount = function(element, value) {
    element.textContent = value;
};

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
    updateStarCount(postElement, snapshot.val());
});

With this JavaScript you can assume HTML page which looks like this:

<html>
  <body>
    <div id="postElement"></div>
  </body>
</html>

Solution 2

Following IgorNikolaev's example... In order to make this post more useful to people having the same problem with Node.js on Raspberry Pi's or as a standalone app (not for a web page).

Thanks to @vzsg, the Firebase Admin SDK may be better suited to my situation.

Steps to create a fully working example are...

This only covers writing to a database, results of which can be seen when logged into Firebase's console.

First, create Firebase admin authentication, then:

var admin = require("firebase-admin");
admin.initializeApp({
    credential:admin.credential.cert("/path/to/credential/cert.json"),
    databaseURL: "databaseURLhere"
});

var db = admin.database();
var ref = db.ref("/");
console.log('DB ref: ' + ref);

var usersRef = ref.child("users");

Use set to create new values in the database. But be careful, set overwrites pre-existing values.

usersRef.set({ //With completion callback.
    alanisawesome: {
      date_of_birth: "June 23, 1912",
      full_name: "Alan Turing"
    },
    gracehop: {
      date_of_birth: "December 9, 1906",
      full_name: "Grace Hopper"
    }
  },
  function(error) { //NOTE: this completion has a bug, I need to fix.
    if (error) {
      console.log("Data could not be saved." + error);
    } else {
      console.log("Data saved successfully.");
    }
});

Append new columns (or change current data) to row with update, but be extra careful to give the paths to column, otherwise all previous columns are overwritten, instead of appending to the table:

usersRef.update({
    "alanisawesome/nickname": "Alan The Machine",
    "gracehop/nickname": "Amazing Grace"
  },
  function(error){
    if(error){
      console.log("Data could not be updated." + error);
    } else {
      console.log("Data updated successfully.");
    }
  });
Share:
11,793
NonCreature0714
Author by

NonCreature0714

Software Engineer. Passionate about Open Source. Love Docker, Swift, Python, Rust, Raspberry Pi, Angular, iOS, and Unity3d.

Updated on June 12, 2022

Comments

  • NonCreature0714
    NonCreature0714 about 2 years

    How to properly set up a value event listener with Firebase, using Node.js?

    I'm reading through Firebase's documents, and have successfully been able to update tables and rows on my Firebase database from both my Mac, and my Raspberry Pi running at the same time, connected to the same Firebase database; however, I'm not able to understand what I need to do with this segment for making a listener on a value event:

    var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
    starCountRef.on('value', function(snapshot) {
        updateStarCount(postElement, snapshot.val());
    });
    

    It's evident to me that I need somehow need to define postElement based on the output:

    FIREBASE WARNING: Exception was thrown by user callback. ReferenceError: postElement is not defined
    

    However, I have not idea what postElement is supposed to be, nor how to define it. Help!

    I've made a very small program and table to simply update/change values. And I changed the program to I can see up console output when a row it changed.

    This is my small user data variable, just so you now how little data I'm trying to change:

    var user = {
        id:Number,
        name:String,
        number:Number
    };
    
    var users = [user];
    

    And this is my change to the documentation code, so I can see something in the console output while Node.js is running:

    var userRef = firebase.database().ref('/users/user' + users[0].id);
    userRef.on('value', function(snapshot){
        firebase.app.updateUserInfo(postElement, snapshot.val());
        console.log('Users' + users[0].name + ' changed.');//<- this is the line I added.
    });
    

    NOTE: updateStarCount function is from the example in the Firebase documentation, meaningful to the example there, which I cautiously assume updates the local Firebase db...

    NOTE2: If updateStarCount is doing some other magic, then it is a documentation flaw with Firebase, because the function isn't defined there. Any help clarifying this documentation would be greatly appreciated.