For my project, I want to fetch data from all documents in a subcollection. And there are multiple documents with this subcollection.
To clarify, this is how my firestore is strctured: I have an events collection which contains multiple documents with doc.id being the event name itself. Each event document has several fields and an attendee subcollection. In the attendee subcollection, each document contains details about the attendee.
I want to map through all documents in the events collection and fetch data about attendees from all of them.
And I want to display this data when the component first renders. So I'm calling the function inside useEffect. Here's what I have tried:
const [attendeeInfo, setAttendeeInfo] = useState({});
const [events, setEvents] = useState([]);
const getEventsData = async () => {
// first of all, we need the name of the user's org
// fetch it from users collection by using the uid from auth
const orgRef = doc(db, "users", auth["user"].uid);
const orgSnap = await getDoc(orgRef);
// now that we have the org name, use that to search events...
// ...created by that org in events collection
const eventsRef = collection(db, "events");
const eventsQuery = query(eventsRef, where("createdBy", "==", orgSnap.data().orgName));
const eventsQuerySnapshot = await getDocs(eventsQuery);
let eventsInfo = [];
eventsQuerySnapshot.forEach((doc) => {
eventsInfo.push(doc.id);
})
setOrg(orgSnap.data().orgName);
setEvents(eventsInfo);
}
const getAttendeesData = (events) => {
console.log(events);
let attendeeInformation = [];
events.forEach(async (event) => {
const attendeesRef = collection(db, "events", event, "attendees");
const attendeesSnap = await getDocs(attendeesRef);
attendeesSnap.forEach((doc) => {
const isItMentor = doc.data().isMentor ? "Yes" : "No";
const isItMentee = doc.data().isMentee ? "Yes" : "No";
const attendeeData = {
name: doc.id,
mentor: isItMentor,
mentee: isItMentee,
};
attendeeInformation.push(attendeeData);
})
})
// console.log(attendeeInformation);
setAttendeeInfo(attendeeInformation);
}
useEffect(() => {
getEventsData();
// console.log(attendeeInfo);
getAttendeesData(events);
}, []);
However, when I console log the events inside my attendeesData function, I get an empty array which means that the events state variable hasn't been updated from previous function.
Can anyone help me solve this?