Estoy probando Firebase por primera vez y pude tomar una "instantánea" de mi colección de Firestore, pero no sé cómo establecer el resultado en una variable de matriz useState . Estoy tratando de dar una matriz de objetos a una variable de matriz useState para poder mostrarla en la interfaz de usuario. Ej: {chat}
Aquí está mi código
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);Lo agradecería profundamente PD cuando "console.log (chat);" y verifique que la consola se produzca un bucle infinito
No estoy seguro si es la causa del problema, pero estás complicando demasiado las cosas aquí:
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); })Mucho más corto y logrando lo mismo (incluso mejor, porque ya no duplica datos) es:
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); })