Caplin YT Caplin YT - 25 days ago 9
Javascript Question

forEach method on Firebase invokes callback with child snapshot with undefined key

It's been a few months I started learning JavaScript, since I am an IOS developer, I prefer Firebase as my backend for my websites too.

So on today's practice, I used to read Firebase data and alert it to myself, I used this code,


Notice: those code's are only examples and used during my work, and it officially comes from Firebase's documentation.


var query = firebase.database().ref("users").orderByKey();

query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
// key will be "ada" the first time and "alan" the second time
var key = childSnapshot.key;
// childData will be the actual contents of the child
var childData = childSnapshot.val();

alert(key); // also tried the (key.value); as well
});


and here is my Firebase structure:
Screenshot

and the output:
Screenshot

Answer Source

It's funny but firebase doesn't update their docs as often as their API changes, even worse if you're using Angular 4+. Try rewriting your code like this below. you need to return a boolean value after iterating a snapshot with forEach:

    var query = firebase.database().ref("users").orderByKey();
    query.once("value", (function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          // key will be "ada" the first time and "alan" the second time
          var key = childSnapshot.key;
          // childData will be the actual contents of the child
          var childData = childSnapshot.val();

          alert(key); // also tried the (key.value); as well
          return true;

      })
)