I am designing a web page that will obtain data from my firestore collection and display each document with its corresponding fields Here is the code:
<table class="table is-striped is-narrow is-hoverable is-fullwidth"> <thead> <tr> <th>Title</th> <th>Author</th> <th>AR Level</th> </tr> </thead> <tbody id="myTable"> </tbody> </table>
here is the JS:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR") .get() .then( function(querySnapshot){ querySnapshot.forEach(function(doc){ dataObj = doc.data() console.log(dataObj) buildTable(dataObj) function buildTable(data){ var table = document.getElementById('myTable') for (var i = 0; i < data.length; i++){ var row = `<tr> <td>${data[i].Title}</td> <td>${data[i].Author}</td> <td>${data[i].Points}</td> </tr>` table.innerHTML += row } } }) } )
Advertisement
Answer
I don’t see why you’re using a for loop in your function. Unless one “Book” document is an Array of items each having the Title/Author/Points fields.
You’re basically looping through the data object as if it’s an array. Chances are, it’s not.
If I’m right, and one “Book” document is object/map containing those three fields, then your code should be like this:
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR") .get() .then(querySnapshot=>{ querySnapshot.forEach(doc=>{ let data = doc.data(); let row = `<tr> <td>${data.Title}</td> <td>${data.Author}</td> <td>${data.Points}</td> </tr>`; let table = document.getElementById('myTable') table.innerHTML += row }) }) .catch(err=>{ console.log(`Error: ${err}`) });