Reputation: 3904
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:
Is this possible?
Thanks.
Upvotes: 1
Views: 1702
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
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
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