user1881482
user1881482

Reputation: 746

Populate HTML table with Firebase Database data

I am currently using Firebase to build a simple e-commerce website and have run into an issue. For the backend I am trying to populate an HTML table with Firebase database data.

Currently, the data is appearing and I am able to populate the body of the table, but at the same time I want to create the headers for the table using the same snapshot. I have been able to do this however it repeats for every record in the database. So two records has two headers.

How can I simply catch the index of the snapshot and only complete the createHeaders function once, or is there a more efficient way of doing this. Below is the JS I am using:

itemsRef.on('value', function(snapshot) {
    snapshot.forEach(function(child) {
        createHeaders(child.val());
        showItems(child.val(), child.key);
    });
});

function createHeaders(data) {
    var html = '';
    html += '<tr>';
    $.each(data, function(key, value) {
        html += '<th>' + key + '</th>';
    });
    html += '<th class="text-right">';
    html += '</tr>';

    $("#tableHeaders").append(html);
}

function showItems(data, key) {
    var html = '';
    html += '<tr>';
    $.each(data, function(key, value) {
        html += '<td>' + value + '</td>';
    });
    html += '<td class="text-right"><a href="/" class="btn btn-primary btn-sm"><i class="fa fa-pencil"></i> Edit</a> <a href="/" class="btn btn-danger btn-sm"><i class="fa fa-times"></i> Delete</a></td>';
    html += '</tr>';

    $('#results').append(html);
}

Upvotes: 0

Views: 2878

Answers (1)

FibreChips
FibreChips

Reputation: 124

snapshot.forEach(function(child) {
    createHeaders(child.val());
    showItems(child.val(), child.key);
});

The .forEach function does just what it says: It will run once for each element in the database at the current Reference location.

Since you are calling createHeaders() every time a piece of data is loaded, you will re-create the headers each time as well.

What you could do is create a simple isFirst boolean, and as the forEach is run in order (I assume your column-headers are the first thing to be returned.) then all you would need is something like this:

snapshot.forEach(function(child) {
    if(isFirst){
        createHeaders(child.val());
        isFirst = false; //So it only will run once.
    }

    showItems(child.val(), child.key);
});

(You might need to use an else{} in there as well, I didn't delve too deep into the code.)

Upvotes: 1

Related Questions