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:
JavaScript
x
12
12
1
<table class="table is-striped is-narrow is-hoverable is-fullwidth">
2
<thead>
3
<tr>
4
<th>Title</th>
5
<th>Author</th>
6
<th>AR Level</th>
7
</tr>
8
</thead>
9
<tbody id="myTable">
10
</tbody>
11
</table>
12
here is the JS:
JavaScript
1
24
24
1
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
2
.get()
3
.then(
4
function(querySnapshot){
5
querySnapshot.forEach(function(doc){
6
dataObj = doc.data()
7
console.log(dataObj)
8
buildTable(dataObj)
9
function buildTable(data){
10
var table = document.getElementById('myTable')
11
12
for (var i = 0; i < data.length; i++){
13
var row = `<tr>
14
<td>${data[i].Title}</td>
15
<td>${data[i].Author}</td>
16
<td>${data[i].Points}</td>
17
</tr>`
18
table.innerHTML += row
19
}
20
}
21
})
22
}
23
)
24
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:
JavaScript
1
18
18
1
db.collection("books").where("ItemType", "==", "Book").where("Program", "==", "AR")
2
.get()
3
.then(querySnapshot=>{
4
querySnapshot.forEach(doc=>{
5
let data = doc.data();
6
let row = `<tr>
7
<td>${data.Title}</td>
8
<td>${data.Author}</td>
9
<td>${data.Points}</td>
10
</tr>`;
11
let table = document.getElementById('myTable')
12
table.innerHTML += row
13
})
14
})
15
.catch(err=>{
16
console.log(`Error: ${err}`)
17
});
18