Home > Mobile >  How to use a conditional for all childs in Firebase
How to use a conditional for all childs in Firebase

Time:07-01

The code below is what I have been trying to do but the dbRef.on("child_added... executes after the ending check. I know why this is happening so how could I do a similar conditional with every child in a firebase path at once and then execute a check afterward. Thanks.

let dbRef = firebase.database().ref("/ExamplePath");
let found = false;
dbRef.on("child_added", (child) => {
     if (child.val().test == testingVal) {
          console.log("Found One!");
          found = true;
     }
});

if (found) {
     console.log("Finished!");
}else{
     console.log("Nope!");
}

CodePudding user response:

The child_added handler is called for each child, and there is no way inside it to know whether this was the last child. For that you'll want to listen to the value event.

So one options is:

let dbRef = firebase.database().ref("/ExamplePath");
let found = false;
dbRef.on("child_added", (child) => {
     if (child.val().test == testingVal) {
          console.log("Found One!");
          found = true;
     }
});

dbRef.on("value", (snapshot) => {
    if (found) {
         console.log("Finished!");
    }else{
         console.log("Nope!");
    }
});

This works great, and Firebase ensures the data gets only downloaded once, despite it being passed to both listeners.


If you prefer you can also do the same with just a value listener:

let dbRef = firebase.database().ref("/ExamplePath");

dbRef.on("value", (snapshot) => {
    let found = false;
    snapshot.forEach((child) => {
         if (child.val().test == testingVal) {
              console.log("Found One!");
              found = true;
         }
    });

    if (found) {
         console.log("Finished!");
    }else{
         console.log("Nope!");
    }
});

The result and efficiency of both approaches is the same, so you should choose whatever is most convenient for your app. For example, I prefer listening to child_ events when I'm responsible for updating each element in the UI directly, as the child_* event tells me pretty directly what to do.

  • Related