1

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.

0

3 Answers 3

2

Yes, that is possible. First you need to left empty ref parameter, so you get all info from root node(all your data). It will trigger at first time it runs by default and will trigger again on any data change, because of parameter'value'. Instead of you you may use child_added, child_changed, child_removed or child_moved to reduce number of times of receiving data from firebase. Example:

firebase.database().ref().on('value', function(snapshot){
    myFunction(snapshot.val());
};

P.S. Don't forget to exact data from snapshot with snapshot.val().

1
  • I like this, its creative. so I can put my node in another one, like this: firebase.database().ref('/users/' + this.userId + '/main/info')
    – Zvi Karp
    Aug 16, 2016 at 15:15
1

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);
  }
});
2
  • Just changed the first 'on' to 'once'. with your answer I don't need to restructure my data layout.
    – Zvi Karp
    Aug 16, 2016 at 15:40
  • Ouch... good point about the once(). I've updated my answer. Aug 16, 2016 at 18:06
0

I am guessing you want to retrieve all existing data from firebase at once then as more data comes in listen for those data changes. If that is your case look at the method once() in firebase

1
  • yea, but I well need to run a 'on' function after the once is finished. how do I do that?
    – Zvi Karp
    Aug 16, 2016 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.