1

I'm trying to iterate through a response from a firebase db and then populate a <select> with the options that come back. However, when I receive the response from firebase and put it into an array, I cannot iterate through it, as the array length is returned as 0. Here is my code:

    renderChoices() {
          var data_list = []
          firebase.database().ref("orgs").once("value").then((snapshot) => {
          snapshot.forEach(function(childSnapshot) {
            var key = childSnapshot.key;
            var childData = childSnapshot.val().name;
            data_list.push(childData);
        });   
     });
    console.log(data_list, data_list.length); 
}

In the console, I get [] 0, but when I unpack the array in my devtools, I can see every entry from the db. How can I get this in a format where I can iterate through and render to the page?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
tay_thomp
  • 245
  • 2
  • 12

1 Answers1

2

The data is loaded from the Firebase Database asynchronously. So when your current console.log runs, the data hasn't loaded yet and it logs a length of 0. But the Chrome dev tools are smarter than their own good (in this case) and update the data_list object browser as the data comes in. That is actually a quite handy feature, but very confusing here.

An easy way to see the actual state is to log static JSON:

console.log(JSON.stringify(data_list), data_list.length); 

Now you'll see that data_list is empty and its length is 0.

The way to deal with asynchronous data loading it so reframe your solution. Currently you have code that says "first load the data, then print it". When loading from Firebase (and most of the modern web), I find it easier to frame it was "Start loading the data. When the data comes in, print it."

renderChoices() {
    var data_list = []
    firebase.database().ref("orgs").once("value").then((snapshot) => {
        snapshot.forEach(function(childSnapshot) {
            var key = childSnapshot.key;
            var childData = childSnapshot.val().name;
            data_list.push(childData);
        });   
        console.log(data_list, data_list.length); 
    });
}

Now it will print the data after it is retrieve from Firebase.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hello :D Would you know the answer to this ? https://stackoverflow.com/questions/44758262/how-to-implement-steam-auth-with-firebase – TheProgrammer Jun 27 '17 at 12:03