1

I need to set up an event listener for firebase that listens for the event whenever a new child is added to a node. But looking at firebase's docs, I have yet to find a good solution.

I thought of using the child_added event. But according to the document, "child_added is triggered once for each existing child and then again every time a new child is added to the specified path."

But I don't want the event to be triggered for existing children when the listener starts to run.

child_changed doesn't seem to be a viable option, either. Because the doc says "The child_changed event is triggered any time a child node is modified." So I suppose this won't be triggered when adding a new child.

Any suggestions on how I can set up a listener to be triggered ONLY when a new child is added?

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
NatashaC
  • 512
  • 1
  • 10
  • 22

2 Answers2

3

I think you are looking for something like this:

firebaseDb.child('KeyName').limitToLast(1).on('child_added', yourCallbackFunction);
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
  • This looks right! Thank you! – NatashaC Jul 10 '18 at 14:51
  • Actually this is not quite correct. limitToLast seems to fetch only the last records ordered by key value, not the latest records created under the parent node. Any idea how one can fetch the newest data? – NatashaC Jul 18 '18 at 02:28
  • @NatashaC Isn't last and latest are same? – BlackBeard Jul 18 '18 at 05:24
  • limitToList will fetch the last few children sorted by their keys. So unless the keys are set up as some form of timestamps, it won't give you the newest data. – NatashaC Jul 19 '18 at 12:58
-1

Please have a look the codes below. At first, you need to get Database. And need to add callback function using "child_added" to get updating database.

 function readMessage(data) { 
      // doing something
 }
 $scope.database = firebase.database().ref('database/');
 $scope.database.on('child_added', readMessage);

Hope it should be helpful. Thanks for your reading.

Maosen Hu
  • 60
  • 5