mr.incredible
mr.incredible

Reputation: 4165

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?

Upvotes: 0

Views: 1497

Answers (2)

Arun Raj R
Arun Raj R

Reputation: 2317

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());
});

Upvotes: 1

mr.incredible
mr.incredible

Reputation: 4165

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.

Upvotes: 1

Related Questions