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

121
Visualizações
Giving an array of objects taken from Firebase(Firestore) to a useState array variable

I'm trying out Firebase for the first time and I was able to take a "snapshot" of my collection from Firestore, but I don't know how to set the result to a useState array variable. I'm trying to give an array of objects to a useState array variable so that I can display it on the UI. Ex: {chat}

Here's my code

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

function App() {
  
  const firebaseApp = initializeApp(Config);
  const firestore = getFirestore();
  const [chat, setChat] = useState([]);

  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"
    });
  }
  
  const readData = async () => {

    let new_data = [];

    const chatAppQuery = query(
      collection(firestore, 'chat'),
      orderBy('date')
    ); 

    const chatSnapshot = await getDocs(chatAppQuery);
    
    chatSnapshot.forEach((message) => {
      new_data.push(
        message.data()
      )
    });
    return new_data;
  }

  readData().then((new_data) => {
    new_data.forEach((new_data) => {
      setChat(chat => [...chat, new_data])
    })
  }).catch(error => {
    console.log(error);
  })
  
  console.log(chat);

I'd deeply appreciate it P.S when I "console.log(chat);", and check the console an infinite loop occurs

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Not sure if it's the cause of the problem, but you're overcomplicating things here:

const readData = async () => {

  let new_data = [];

  const chatAppQuery = query(
    collection(firestore, 'chat'),
    orderBy('date')
  ); 

  const chatSnapshot = await getDocs(chatAppQuery);
  
  chatSnapshot.forEach((message) => {
    new_data.push(
      message.data()
    )
  });
  return new_data;
}

readData().then((new_data) => {
  new_data.forEach((new_data) => {
    setChat(chat => [...chat, new_data])
  })
}).catch(error => {
  console.log(error);
})

Much shorter and accomplishing the same (one better even, because it's no longer duplicating data) is:

const readData = async () => {
  const chatAppQuery = query(
    collection(firestore, 'chat'),
    orderBy('date')
  ); 

  const chatSnapshot = await getDocs(chatAppQuery);
  
  return chatSnapshot.docs.map((message) => message.data());
}

readData().then((new_data) => {
  setChat(new_data)
}).catch(error => {
  console.log(error);
})
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