0

It seems like nothing is stored in the array with this code:

(Assume showList is an actual div id; didn't think it was necessary to include those tags in the code)

 var i = 0;
 var array = [];
 var showList = document.getElementById('showList');

firebase.firestore().collection('TV Shows').get().then(snapshot => {

    snapshot.forEach(doc => {

        array[i] = doc.data().show.name;
        i++;
        //console.log(doc.data().show.name);

    });

}); 

showList.innerHTML = array[4];

Funny enough, that commented console.log line works fine and displays all the objects, so I don't understand why I can't store it in the array. A big part of me feels as if it's my direction in using the array and/or i variable, but I tagged it as a firebase/firestore issue as well on the off chance it turns out to be a firebase issue.

If someone could point me in the write direction, I would appreciate it.

1

1 Answer 1

2

.get() is asyncronyous, and at the time you run:

showList.innerHTML = array[4];

array has not been initialized yet.

You either need to use callbacks/promises as mentioned in the linked duplicate, or simply move your call inside the .then() function:

 var showList = document.getElementById('showList');

firebase.firestore().collection('TV Shows').get().then(snapshot => {
    var array = [];
    var i = 0;

    snapshot.forEach(doc => {

        array[i] = doc.data().show.name;
        i++;
        //console.log(doc.data().show.name);

    });
    showList.innerHTML = array[4];

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

2 Comments

Awesome, thanks a lot! Do you know how I could display the array in a table with a loop? Or should I make a separate question for this?
@SalimElouafi Does it really need another question? Loop through the snapshot, and build the HTML (Or use jQuery and generate the items), and append it to the DOM. Plenty of good resources: stackoverflow.com/questions/29322823/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.