I'm trying to get some data from a firestore database and save it into a array in react. This is my code.
const readDocuments = async () => {
const allData = await getDocs(collectionRef);
//console.log(allData);
// allData.forEach((doc) => {
// console.log(doc.id, " => ", doc.data());
// });
setData(allData.docs.map((doc) => ({
...doc.data(), id: doc.id
})))
console.log(data);
//return allData;
};
When I check the console, this is what I get.
Not really sure what I'm doing wrong here. I saw pretty much the same method used in a tutorial. And if I uncomment the foreach loop within the function, it outputs the data properly so I figure it's not a issue with actually retrieving the information.
Edit: The function above is nested in a useEffect hook.
import { useEffect, useState } from "react";
import { collection, getDocs } from "firebase/firestore";
import { db } from "../firebase/config";
const useGetDocs = (collectionName) => {
const [documents, setDocuments] = useState([]);
//Firebase Collection Reference
const postCollectionRef = collection(db, collectionName);
useEffect(() => {
const getDocuments = async () => {
const data = await getDocs(postCollectionRef);
setDocuments(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
};
getDocuments();
}, []);
return { documents };
}
export default useGetDocs;
This is the full file that I used and it works now. Not necessarily sure what was wrong before but the main change I made was created it as a custom hook using the 'use' keyword which might have had something to do with it. I'm no expert by any means and could still be doing something wrong but hopefully this helps someone if they have a similar issue.
Cheers!