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?
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());
});
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());
});
I tried other answers way but invoked at least once for last child. If you have a time key in your data, you can do this way.
ref.orderByChild('createdAt').startAt(Date.now()).on('child_added', ...
Since calling the ref.push()
method without data generates path keys based on time, this is what I did:
// Get your base reference
const messagesRef = firebase.database().ref().child("messages");
// Get a firebase generated key, based on current time
const startKey = messagesRef.push().key;
// 'startAt' this key, equivalent to 'start from the present second'
messagesRef.orderByKey().startAt(startKey)
.on("child_added",
(snapshot)=>{ /*Do something with future children*/}
);
Note that nothing is actually written to the reference(or 'key') that ref.push()
returned, so there's no need to catch empty data.
Swift3 Solution:
You can retrieve your previous data through the following code:
queryRef?.observeSingleEvent(of: .value, with: { (snapshot) in
//Your code
})
and then observe the new data through the following code.
queryRef?.queryLimited(toLast: 1).observe(.childAdded, with: { (snapshot) in
//Your Code
})