Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase: How to run a callback after all the initial "child_added" calls?

When listening on the "child_added" event with:

ref.on("child_added", function (snapshot) {

});

This callback function will initially run once for every child that exists in the reference.

This event will be triggered once for each initial child at this location, and it will be triggered again every time a new child is added.

https://firebase.google.com/docs/reference/node/firebase.database.Reference

I want to take advantage of this fact along with the ordering functions in order to construct an ordered array:

orderedArray = [];

ref.orderByValue("rating").on("child_added", function (snapshot) {
    orderedArray.push(snapshot.val())
});

// how do I run a callback after the last child has been added?

However, there is no way (to my knowledge) to tell the last time the child_added callback has been called, thus I can't accurately run my own callback after the the last child has been added to my array.


Here's my workaround to this right now:

orderedArray = [];

ref.orderByValue("rating").on("child_added", function (snapshot) {
    orderedArray.push(snapshot.val())
});

setTimeout(function() {

    ref.off("child_added") // unbind event
    callback()

}, 3000)

This is pretty sketchy, especially in the case that it'll take more than 3 seconds to get all the data from the database.

Any ideas here?

like image 616
octopod Avatar asked Dec 10 '22 16:12

octopod


1 Answers

You can iterate over parent snapshot and order the children into an array using DataSnapshot.forEach:

const ref = firebase.database().ref().child('items');
const items = [];
ref.once('value', snap => {
  snap.forEach(item => { items.push(item) });
  console.log(items);
});

Since you're calling ref.off() to read the data once, it makes sense that to use the .once() method and iterate of the parent snapshot instead.

like image 99
David East Avatar answered Feb 15 '23 22:02

David East