Leonardo Carvalho
Leonardo Carvalho

Reputation: 63

Calling Firebase database child() returns "undefined" in Javascript

This is what I have

Firebase Database:

setores: {
    -KkBgUmX6BEeVyrudlfK: {
        id: '-KkBgUmX6BEeVyrudlfK',
        nome: 'test'
    }
    -KkDYxfwka8YM6uFOWpH: {
        id: '-KkDYxfwka8YM6uFOWpH',
        nome: 'test1'
    }
}

JavaScript

var setorRef = firebase.database().ref().child("setores");
/* DELETE ROW */
$("#tbody_setores").on('click','.delete-btn', function(e){
    var $row = $(this).closest('tr'),
       rowId = $row.data('id');

    var rowId = $row.data('id');
    //it should remove the firebase object in here
    setorRef.child(rowId).remove()
    .then(function() {
      //after firebase confirmation, remove table row
      $row.remove();
    })
    .catch(function(error) {
      console.log('Synchronization failed');
    });  
});

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

  var setorKey = snap.child("id").val();
  var nome = snap.child("nome").val();

  $("#tbody_setores").append("<tr data-id'"+setorKey+">"+
                                "<td class='mdl-data-table__cell--non-numeric'>" + nome + "</td>" +
                                "<td class='mdl-data-table__cell--non-numeric'>"+
                                  "<div buttons>"+
                                    "<button class='delete-btn mdl-button mdl-js-button mdl-button--icon mdl-button--colored'><i class='material-icons'>delete</i></button>"+" "+
                                  "</div>"+
                                "</td>"+
                              "</tr>");
});

Now, what I want to do with this code is: when I click on the remove button that has been appended on the table, it should remove the row and the corresponding object in the database. I was using this same code on another table (here), and it works just fine, but on this one, the rowId is returning undefined instead of the id.

Upvotes: 1

Views: 395

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Looks like you have a couple of typos in your HTML (in the data-id attribute):

$("#tbody_setores").append("<tr data-id'"+setorKey+">"+

which should probably read like this:

$("#tbody_setores").append("<tr data-id='"+setorKey+"'>"+ 

this would nicely explain why rowId is returning undefined instead of the id ;)

Upvotes: 2

Related Questions