Leonardo Carvalho
Leonardo Carvalho

Reputation: 63

Remove object from firebase using JavaScript

I am setting some objects on firebase-database, and showing them on a HTML table with 'child_added' and append() to dynamically add them as soon as they are added to the database, and there has to be a delete button on each row of the table, but the problem is, I can't get this delete button to work...

This is how the database structure looks like:

Assets: {
    -KkBgUmX6BEeVyrudlfK: {
        id: '-KkBgUmX6BEeVyrudlfK',
        name: 'John',
        brand: 'HP'
    }
    -KkDYxfwka8YM6uFOWpH: {
        id: '-KkDYxfwka8YM6uFOWpH',
        name: 'Jack',
        brand: 'Dell'
    }
}

And this is my index.js:

var rootRef = firebase.database().ref().child("Assets");
$("#table_body").on('click','.delete-btn', function(e){
    var $row = $(this).closest('tr'),
       rowId = $row.data('id');
    var assetKey = rootRef.child("id");
    //it should remove the firebase object in here
    rootRef.child(assetKey).remove()
    //after firebase confirmation, remove table row
    .then(function() {
      $row.remove();
    })
    //Catch errors
    .catch(function(error) {
      console.log('ERROR');
    });  
});

rootRef.on("child_changed", snap => {

  var assetKey = snap.child("id").val();
  var name = snap.child("name").val();
  var brand = snap.child("brand").val();

$("#table_body").append("<tr data-id='"+assetKey+"'>"+
                          "<td>" + name + "</td>" +
                          "<td>" + brand + "</td>" +

                          "<td><div buttons>"+
                                  "<button class='delete-btn>delete</button>"+
                                  "</div></td></tr>");
});

The assetKey that is inside rootRef.on("child_changed", snap => { if showed on console.log returns the right value for the object key, but the 'assetKey' on $("#table_body").on('click','.delete-btn', function(e){ is not working properly...

Upvotes: 1

Views: 3266

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19349

This line looks wrong to me (trying to get the nonexistent id property of the top level Assets node):

var assetKey = rootRef.child("id");

Try this instead:

var rowId = $row.data('id');
rootRef.child(rowId).remove()
...

Upvotes: 2

Related Questions