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.

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Blue Dec 17 '18 at 02:30

1 Answers1

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];

});
Blue
  • 22,608
  • 7
  • 62
  • 92
  • 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? – Salim Elouafi Dec 17 '18 at 04:28
  • @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: https://stackoverflow.com/questions/29322823/populate-table-from-array-using-jquery – Blue Dec 17 '18 at 04:34