简体   繁体   中英

firebase child_added event issue

I want to get recently added child node from firebase database at the moment of pushing but not the last child node of database at all.

The problem is that the typical child_added event gets the last child anyway even on page loading at first time.

This code will output last child even if at this time no new nodes were added.

firebase.database().ref("coupons").limitToLast(1).on('child_added', function(snapshot) {
   console.log(snapshot.val());
});

This "hack" is working for me now but how to rewrite it in appropriate way?

firebase.database().ref().on('child_changed', function() { // listen only when there are some changes in entire db, the key solution for this purpose.
   firebase.database().ref("coupons").limitToLast(1).on('child_added', function(snapshot) {
      console.log(snapshot.val());
   });
});

So, why just child_added listener works if at this time no new nodes were added?

I solved this by assigning a bool var for checking the first time initiation to skip firebase event on page load.

var child_added_first = true;
firebase.database().ref("coupons").limitToLast(1).on('child_added', function(snapshot) {
   if (!child_added_first) {
      console.log(snapshot.val());
   }
   child_added_first = false;
});

Furthermore, 'child_added' is triggered by firebase on the client when I just simply remove some node from my firebase db in console panel. Why?

Seems it's time to look at some other realtime SaaS databases with more friendly api and documentation.

You can try the following code, if you have a time node.

firebase.database().ref("coupons")
.orderByChild('time').startAt(Date.now())
.limitToLast(1).on('child_added', function(snapshot) {
   console.log(snapshot.val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM