Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase child_added only get child added

Tags:

firebase

From the Firebase API:

Child Added: This event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added.

Some code:

listRef.on('child_added', function(childSnapshot, prevChildName) {     // do something with the child }); 

But since the function is called once for each child at this location, is there any way to get only the child that was actually added?

like image 448
Matt Robertson Avatar asked Aug 03 '12 03:08

Matt Robertson


People also ask

How do I find the number of children in Firebase?

Show activity on this post. retrieve childs of Day 1 to an array and count the array that ll be the no of child. Show activity on this post. add another lister to days that will give you all matches you played on a day.

How do I add a child to realtime database?

By combining the push() and child() methods, you can create multiple lists of children in the database: mDatabase. child("numbers"). push().


2 Answers

To track things added since some checkpoint without fetching previous records, you can use endAt() and limit() to grab the last record:

// retrieve the last record from `ref` ref.endAt().limitToLast(1).on('child_added', function(snapshot) {     // all records after the last continue to invoke this function    console.log(snapshot.name(), snapshot.val());  }); 
like image 82
Kato Avatar answered Oct 01 '22 02:10

Kato


limit() method is deprecated. limitToLast() and limitToFirst() methods replace it.

// retrieve the last record from `ref` ref.limitToLast(1).on('child_added', function(snapshot) {     // all records after the last continue to invoke this function    console.log(snapshot.name(), snapshot.val());    // get the last inserted key    console.log(snapshot.key());  }); 
like image 20
tibeoh Avatar answered Oct 01 '22 02:10

tibeoh