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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hello :D Would you know the answer to this ? stackoverflow.com/questions/44758262/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.