Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda