Home > Software engineering >  Pull data in from firestore with React
Pull data in from firestore with React

Time:07-03

From my understanding, if i use the code below to retrieve what i have in firestore, it should be an array. I tried

data.forEach((doc) => {
  console.log(doc.id, " => ", doc.data());
}); 

standard example code from google firestore. I found the object in console log is the array i need to get from the db.

Now, this is my code

import React, { useEffect, useState } from 'react';
import { getDocs, collection } from 'firebase/firestore';
import { db } from '../firebase-config';


const Home = () => {

    const [postList, setPostList] = useState([]);
    const postsCollectionRef = collection(db, "data");

    useEffect(() => {
        const getPosts = async () => {
            const data = await getDocs(postsCollectionRef);
            data.forEach((doc) => {
                setPostList({ ...doc.data() });
            });
        };
        getPosts();
        console.log(postList);
    }, []);


    return (
        <div>{postList[0].Example}</div>
    );
};

export default Home;

why it returns an empty array?

enter image description here

CodePudding user response:

When you call

setPostList({ ...doc.data() });

It will overwrite the old state, so what you would need to do is to create an array from Firestore data and then set that whole array inside of state like below

    useEffect(() => {
    const getPosts = async () => {
        const data = await getDocs(postsCollectionRef);
        let postListArray = []
        data.forEach((doc) => {
            const post = { ...doc.data() } 
            postListArray.push(post)
        });
        setPostList(postListArray)
    };
    getPosts();
    console.log(postList);
}, []);

CodePudding user response:

You can use map() with snapshot.docs (array of DocumentSnapshots) as shown below:

const snapshot = await getDocs(postsCollectionRef);

const data = snapshot.docs.map((doc) => ({ id: doc.id, ...d.data() }))

setPostList(data);
  • Related