Firebase child_added only get child added
Solution 1:
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());
});
Solution 2:
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());
});
Solution 3:
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.