Currently puzzled by the behavior of this array. Despite my efforts to find an answer, I haven't had any luck so far. I initialize var allMenuItems = []; at the top and then in getMenuItems(), I push multiple new class objects. However, when I call console.log(allMenuItems[0]); it returns as undefined. Yet when I simply call .log(allMenuItems), it shows that the array is populated. Not entirely sure where I'm going wrong, but I suspect it's related to how I'm storing/reading the array. Any help would be greatly appreciated.
Note: The script is being imported using defer
var allMenuItems = [];
var imgRoot;
var price;
var time;
var menuItemTemplate = document.querySelector('#MenuItemTemplate');
var pizzaData = db.collection("MenuItems").doc("Pizzas");
var pizzaInfo = db.collection("MenuItems").doc("Pizzas").collection("Info");
var pizzaMenu = document.getElementById("PizzaMenu");
getMenuItems(pizzaInfo, pizzaMenu, pizzaData);
var wingsData = db.collection("MenuItems").doc("Wings");
var wingsInfo = db.collection("MenuItems").doc("Wings").collection("Info");
var wingsMenu = document.getElementById("WingsMenu");
getMenuItems(wingsInfo, wingsMenu, wingsData);
var sidesData = db.collection("MenuItems").doc("Sides");
var sidesInfo = db.collection("MenuItems").doc("Sides").collection("Info");
var sidesMenu = document.getElementById("SidesMenu");
getMenuItems(sidesInfo, sidesMenu, sidesData);
function getMenuItems(query, menuDiv, dataQuery) {
getItemData(dataQuery);
query.get().then((querySnapshot) => {
querySnapshot.forEach((doc) =>
{
var menuItemClone = menuItemTemplate.content.cloneNode(true);
menuItemClone.querySelector('#MenuItemImg').src = imgRoot + doc.data().imgSrc;
menuItemClone.querySelector('#MenuItemName').innerText = doc.data().name;
menuItemClone.querySelector('#MenuItemDesc').innerText = doc.data().desc;
menuItemClone.querySelector('[class*="btn-danger"]').id = "MenuItem" + doc.id;
menuDiv.appendChild(menuItemClone);
var newMenuItem = new MenuItem(doc.id, imgRoot + doc.data().imgSrc, doc.data().name, doc.data().desc, price, time)
allMenuItems.push(newMenuItem);
});
});
}
function getItemData(query) {
query.get().then((doc) => {
if (doc.exists) {
imgRoot = doc.data().imgRoot;
price = doc.data().price;
time = doc.data().time;
} else {
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
}
function getMenuItemById(find)
{
console.log(find);
return allMenuItems.find(({ id }) => id === find);
}
class MenuItem
{
constructor(id, imgSrc, name, desc, price, time)
{
this.id = id;
this.imgSrc = imgSrc;
this.name = name;
this.desc = desc;
this.price = price;
this.time = time;
this.amount = 0;
}
}
console.log(allMenuItems[0]);