Salim Elouafi
Salim Elouafi

Reputation: 9

Issue creating an array of Firestore objects

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.

Upvotes: 0

Views: 40

Answers (1)

Blue
Blue

Reputation: 22911

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

});

Upvotes: 2

Related Questions