Benjamin Sommer
Benjamin Sommer

Reputation: 1268

Firebase - Generate table from database data

I would like to know how to create a table like thisthisfrom some data in a firebase database like this this

There would need to be a column for ID, Title, Number of Answers, Correct Answer and Type. Preferably this should be done using jQuery.

Thank you in advance.

Upvotes: 1

Views: 5491

Answers (1)

JayJamesJay
JayJamesJay

Reputation: 623

Get data

Read the firebase database documentation and references.

The basic firebase read operation looks like this:

var ref = firebase.database().ref("location");
ref.once("value")
  .then(function(snapshot) {
    var key = snapshot.key;
    var value = snapshot.val();

    console.log(key + ": " + value);
  });

Of course you have to add scripts for firebase and firebase database before.

If you want to loop through an data you can use forEach function, for example:

var query = firebase.database().ref("location2");

query.once("value").then(function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var key = childSnapshot.key;
    var value = childSnapshot.val();

    console.log(key + ": " + value);
  });
});

Table

You can create table dynamically using JS - functions like createElement and createDocumentFragment

For example:

var fragment = document.createDocumentFragment();
var animalsArray = ["Elephant", "Dog", "Cat"];

var table = document.createElement("table");

for (var i = 0; i < animalsArray.length; i++) {
  var tr = document.createElement("tr");
  var td = document.createElement("td");

  td.textContent = animalsArray[i];

  tr.appendChild(td);
  table.appendChild(tr);
}

fragment.appendChild(table);
document.body.appendChild(fragment);

Table built from data in Firebase database

And now connect concepts above together. Create a table. Get data from firebase database. At every ireration over this data: create new table row with cells built from key and value of an element. In example below I used for loop to not duplicate the same operation for every cell.

Full example:

Data tree in Firebase Database:

{
  "location2" : {
    "hello" : "world",
    "hi" : "Mark"
  }
}

Code:

var fragment = document.createDocumentFragment();
var table = document.createElement("table");

var query = firebase.database().ref("location2");

query.once("value").then(function(snapshot) {
  snapshot.forEach(function(childSnapshot) {
    var tr = document.createElement("tr");
    var trValues = [childSnapshot.key, childSnapshot.val()];

    for (var i = 0; i < trValues.length; i++) {
      var td = document.createElement("td");

      td.textContent = trValues[i];
      tr.appendChild(td);
    }

    table.appendChild(tr);
  });
});

fragment.appendChild(table);
document.body.appendChild(fragment);

Upvotes: 2

Related Questions