Me gustaría acceder a mi matriz después de consultar mi base de datos en tiempo real, pero se registra una matriz vacía después de extraer un elemento y agregarlo a mi matriz. ¿Sabes qué puede estar causando esto? A continuación se muestra mi código:
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);} }Lo más probable es que console.log se ejecute antes que array_Message_.push, porque db.ref( users ).on y otras operaciones similares son operaciones asíncronas. Entonces, en lugar de escribir semessageWithPhotos al final, escríbalo en la última devolución de llamada
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);}}
al igual que.