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

153
Views
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 answers
Answer question

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 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!