I have a function (createList()) that creates an array from Firebase database values, and a function that posts the array as an HTML object (postList()).
The array it returns seems to be fine (see "returned array" below) while debugging (console.log(array)) and I can see the values in the debugger displayed correctly, yet array[0] returns "undefined" and array.length returns "0", so the list isn't displayed.
Any solutions?
async createList(){
var composedArray = [];
const id = document.getElementById('joinCode').innerHTML;
var player_count = null;
firebase.database().ref('lobbies/' + id + '/playerCount/').once('value', (snapshot) => {
const data = snapshot.val();
player_count = data;
}).then(function() {
for(var i = 1; i <= player_count; i++){
var iStr = String(i);
const player_names_snapshot = firebase.database().ref('lobbies/' + id + '/players/' + iStr);
player_names_snapshot.once('value', (snapshot) => {
const data = snapshot.val();
composedArray.push(data);
});
}
});
return composedArray;
},
async postList(array){
console.log(array);
console.log(array[0]);
var list = document.createElement('ul');
for(let i = 0; i < array.length; i++){
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
const listContainer = document.getElementById('listWrap_players');
this.removeAllChildNodes(listContainer);
return list;
},
The function that calls these functions:
async mountedCall(){
var composedArray = [];
composedArray = await this.createList();
document.getElementById('listWrap_players').appendChild(await this.postList(composedArray));
},
Returned array + debugger image on lighshot: https://prnt.sc/23q4jra
My first thought was that my "array" is not actually an array and that I've maybe created a different object, but I couldn't figure out why, and this worked just fine before I started to migrate the app from Firestore to Realtime database, so I'm kinda lost.
The problem is not with the values returned from the database. The values are loaded into the array correctly and in time (parameter array has a value when postList() is called (as proven by the correct execution of console.log(array)), but the values in the array, although there (see debugger image) cannot be reached the usual way, through an index (array[x]) nor does .length return the length of the array.