简体   繁体   中英

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!

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]);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM