Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
How to use a conditional for all childs in Firebase

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!");
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!