Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
Objects taken from Firebase are inaccessible after being pushed into an array through a forEach loop

I've been trying to create a chat app using react and firebase just for practice since I wanted to try out Firebase, and although I'm able to print out the array of objects that I retrieved into the console, I can't seem to access those objects directly... For example:

if I code "console.log(testArray);" this is what displays in the console, which is all good

0: {name: 'JohnDoe', profile_image: 'imaginary image URL', date: it, message: 'This is my first message to Firebase!'}

but if I try console.log(testArray[0]); it displays undefined in the console

Here's my code

import Config from './config';
import { initializeApp } from "firebase/app";
import { 
  getFirestore, 
  addDoc, 
  getDocs, 
  collection, 
  query, 
  orderBy 
} from "firebase/firestore";

function App() {
  
  const firebaseApp = initializeApp(Config);
  const firestore = getFirestore();

  const chat_collection = collection(firestore, "chat");
  const addData = () => {
    addDoc(chat_collection, {
      date: new Date(),
      message: document.getElementById("message").value,
      name: "JohnDoe",
      profile_image: "imaginary image URL"
    });
  }
  
  let testArray = [];
  
  const readData = async () => {
    const chatAppQuery = query(
      collection(firestore, 'chat'),
      orderBy('date')
    ); 

    const chatSnapshot = await getDocs(chatAppQuery);
    
    chatSnapshot.forEach((message) => {
      testArray.push({
        name: message.data().name,
        profile_image: message.data().profile_image,
        date: message.data().date,
        message: message.data().message
      });
    });
  }
  readData();
  console.log(testArray);
  console.log(testArray[0]);

My first time asking for help on here, I'd deeply appreciate it!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Since readData is an async function, you need to use await (or then() to wait for it results.

So:

await readData();
// 👆
console.log(testArray);
console.log(testArray[0]);

If you're in a context where you can't use async/await, you can also use then:

readData().then(() => {
         // 👆
  console.log(testArray);
  console.log(testArray[0]);
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda