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

207
Visualizações
Failing to add item into array react native

I would like to access my array after querying my realtime database but an empty array is logged after extracting an item and adding it into my array. Do you know what may be causing this? Below is my code:

 const chatBox = async () => {

     let array_Message_ = [];
     try {
      setLoading(true);
      db.ref(`messages/`).once(`value`, snapshot => {
        if(snapshot.exists() == true) {
            snapshot.forEach(function(childSnapshot){
                if(childSnapshot.key.includes(auth().currentUser.uid)){
                   var otherUserId = childSnapshot.key.replace(auth().currentUser.uid,"");
                   db.ref('messages').child(childSnapshot.key).orderByChild("sentWhileBlocked").equalTo(false).limitToLast(1).on('value',(dataSnapshots) => {
                   if (dataSnapshots.val()) {
                       for (let key in dataSnapshots.val()) {
                          db.ref(`users`).on(`value`, user_snapshot => {
                           user_snapshot.forEach(function(user_childSnapshot){
                              if(otherUserId == user_childSnapshot.key) {
                                    array_Message_.push({text:dataSnapshots.val()[key].text,timestamp:dataSnapshots.val()[key].timestamp, username: user_childSnapshot.val().username, messageKey:key, key:dataSnapshots.key})
                              }
                           })
                         });
                       }
                    }
                });
              }
           })
            console.log("array: "+JSON.stringify(array_Message_))
            setmessagesWithPhotos(array_Message_);
       }
    });
      } catch(err) {console.log(err);}
 }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

console.log most probably will run before array_Message_.push, because db.ref(users).on and other such operations are async operations. So instead of writing semessageWithPhotos at the end write it in the last callback

 const chatBox = async () => {

 let array_Message_ = [];
 try {
  setLoading(true);
  db.ref(`messages/`).once(`value`, snapshot => {
    if(snapshot.exists() == true) {
        snapshot.forEach(function(childSnapshot){
            if(childSnapshot.key.includes(auth().currentUser.uid)){
               var otherUserId = childSnapshot.key.replace(auth().currentUser.uid,"");
               db.ref('messages').child(childSnapshot.key).orderByChild("sentWhileBlocked").equalTo(false).limitToLast(1).on('value',(dataSnapshots) => {
               if (dataSnapshots.val()) {
                   for (let key in dataSnapshots.val()) {
                      db.ref(`users`).on(`value`, user_snapshot => {
                       user_snapshot.forEach(function(user_childSnapshot){
                          if(otherUserId == user_childSnapshot.key) {
                                array_Message_.push({text:dataSnapshots.val()[key].text,timestamp:dataSnapshots.val()[key].timestamp, username: user_childSnapshot.val().username, messageKey:key, key:dataSnapshots.key})
                          }
                       })
                       console.log("array: "+JSON.stringify(array_Message_))
                       setmessagesWithPhotos(array_Message_);
                     });
                   }
                }
            });
          }
       })
   }
});
  } catch(err) {console.log(err);}

}

like so.

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