Firebase child_added only get child added

Viewed 52588

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?

5 Answers

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.

Related