Zvi Karp Zvi Karp - 3 months ago 12
Javascript Question

Firebase run script after retrieving existing data

I have a function in js that needs to refresh after I retrieve data from Firebase.

firebase.database().ref('/users/' + this.userId + '/info').on('child_added', function(snapshot){
this.myFunction();
}.bind(this));


The problem is that the data in Firebase is very large so I don't what to run the function lots of times. This is how I what it to run:


  1. Retrieve ALL EXISTING data from Firebase.

  2. Run the function (once).

  3. Every time more data comes in from Firebase, run the function again.



Is this possible?

Thanks.

Answer

Yevgen's answer is one way to do this. But it means you'll be processing all children on each change, which may not be what you want.

An alternative is to process the initial children using a value event and then the subsequent changes with child_ events. You can use the guarantee that the value event will fire after all the related child_ events to detect whether the initial payload is done.

var isInitialValueDone = false

ref.once('value', function(snapshot) {
  snapshot.forEach(function(child) {
    console.log('Do something with '+child.key);
  });
  isInitialValueDone = true;
});
ref.on('child_added', function(snapshot) {
  if (isInitialValueDone) {
    console.log('Do something with '+snapshot.key);
  }
});