I'm trying to generate an array of data from my Firebase database and populate a HTML page with the result.
This is the layout of my database:
MYAPP
|_______chat
|
|_______users
|_____2eD8O9j2w
| |____email
| |____first_name
| |____last_name
|
|_____7d73HR6d
|_____9ud973D6
|_____Kndu38d4
I want to be able to get an array of all the "email" and "first_name" fields inside users
, and then automatically create and populate a list in HTML from this data. (Kind of like creating a contact list, where there would be two divs per row: <td><div>first_name</div><div>email</div></td>
)
This is my current attempt a populating the HTML page with the data:
HTML
(Is it possible to create and populate these rows automatically inside the Javascript, instead of creating empty ones in the HTML code?)
<div>
<section>
<table>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</section>
</div>
Javascript
function createContactList(){
var elements = document.getElementsByTagName('td');
var contacts = [];
// Get a database reference to the users section
var ref = firebase.database().ref().child('/users');
ref.on("value", function(element) {
return function (snapshot) {
console.log(snapshot.val());
// Loop through each HTML tag
for(var i = 0; i < elements.length; i++){
element.innerHTML = snapshot.val();
var tester = snapshot.val();
console.log(tester.email); // This returns "undefined"
console.log(snapshot.val()); // This returns a list of User IDs
console.log(snapshot.val().email); // This returns "undefined"
console.log(snapshot.val(email)); // This shows the error: ``firebase Uncaught ReferenceError: email is not defined``
var createarraytest = snapshot.email;
contacts.push({email: createarraytest});
}
}(elements[i]),
function (errorObject) { // Deal with errors
console.log("The read failed: " + errorObject.code);
});
}
console.log(contacts);
}
When I run this function, it the following list appears on the HTML page:
[OBJECT OBJECT]
[OBJECT OBJECT]
[OBJECT OBJECT]
[OBJECT OBJECT]
[OBJECT OBJECT]
console.log(snapshot.val());
shows a list of the randomized user IDs. In an attempt to access the email
and first_name
data for each ID I've tried the following:
var tester = snapshot.val();
console.log(tester.email); // This returns "undefined"
console.log(snapshot.val().email); // This returns "undefined"
console.log(snapshot.val(email)); // This shows the error: ``firebase Uncaught ReferenceError: email is not defined``
I'm used to using arrays in Javascript with an SQL database, but I don't know how to access the data contained within the random user ID strings Firebase creates in this noSQL database.
I've tried following the docs and the answer posted here: Proper way to store values array-like in Firebase but I've so far been unable to get it to work.
Any help getting this to work would be really appreciated, thank you in advance!