mardi 4 août 2020

Why does using "once" instead of "on" break things here?

So I built an app where you enter the name of your favorite book and author in a form, and it generates a card with that information.

There's a checkbox on the form to mark if you own it and a "remove" button.

It works with an addtoLibrary() function that takes the info from the form, puts it into an object and that object into firebase.

Within that function, I have another function called render() which takes the info from firebase and puts it into the DOM.

Next I added another function called retrievefromDatabase() which also incorporates the render() function, and loops through the list of objects to draw cards for the items that exist in the database.

The problem I'm facing now is that whenever the checkbox is checked or unchecked, the retrievefromDatabase() function activates and draws another card.

I think if I could change the on in the second database call to once here, that would solve my problem. But when I do that, all the fields in my card render to "undefined."

I'm not sure why it's even doing that, because the initial database call is a once that loops over every object key, and there are no new object keys when the checkbox changes. It's just a change of state for the object.

function retrievefromDatabase() {
  firebase.database().ref("Book").once("value", gotData);
      function gotData(Book) {
      var books = Book.val();
      var keys = Object.keys(books);
        for (var i = 0; i < keys.length; i++) {
          firebase.database().ref("Book/" + keys[i]).on("value", function(snapshot) {
          newPostKey = snapshot.key;    
          function oldBook(title, fname, lname, pubDate, contrib, own) {
            this.title = title;
            this.fname = fname;
            this.lname = lname;
            this.pubDate = pubDate;
            this.contrib = contrib;
            this.own = own;
          };          
          var archiveBook = new oldBook(snapshot.val().title, 
          snapshot.val().fname, 
          snapshot.val().lname, 
          snapshot.val().pubDate,
          snapshot.val().contrib,
          snapshot.val().own);
          render();
        })}}};



Aucun commentaire:

Enregistrer un commentaire