React component does't display options after setting state, firestore returning empty array with object in it? I'm confused
Have this problem going on where I fetch data from firestore, then setState with that data, for some reason my component won't re render to then display that data. It'll just be blank. fetchData is my firebase function, it returns an empty array which my console is showing as empty, but there's objects in there which is confusing. photo of empty array with objects from firestore
const dataFetching = (data) => {
const x = fetchData(data);
setData(x);
};
// fetchData firestore function
export const fetchData = (applicants) => {
const applicantData = [];
for (let i = 0; i < applicants.length; i++) {
const x = firestore.collection("users").doc(applicants[i]).get();
x.then((user) => applicantData.push(user.data()));
}
return applicantData;
};
Solution 1:
firestore.collection("users").doc(applicants[i]).get()
returns a promise that doesn't get awaited. The for loop therefore finishes iterating before the promises get resolved. At the time of the return applicantData;
the array is still empty so setData
is receiving an empty array.
I would change the fetchData
function to something like this:
export const fetchData = async (applicants) => {
const applicantData = [];
for (let i = 0; i < applicants.length; i++) {
const user = await firestore.collection("users").doc(applicants[i]).get();
applicantData.push(user.data())
}
return applicantData;
};
And the dataFetching
function to something like this:
const dataFetching = async (data) => {
const x = await fetchData(data);
setData(x);
};