Zvi Karp
Zvi Karp

Reputation: 3904

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.

Upvotes: 1

Views: 1702

Answers (3)

Frank van Puffelen
Frank van Puffelen

Reputation: 598797

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);
  }
});

Upvotes: 1

Yevgen
Yevgen

Reputation: 4709

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().

Upvotes: 2

David
David

Reputation: 1159

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

Upvotes: 0

Related Questions