I've been breaking my head today over this function. All I am trying to do is get all documents from my collection in Firebase and put this in an array of documents like the fakeProjectMetaData.
There's similar questions around here:
- How do I return the response from an asynchronous call?
- How to return value from an asynchronous callback function?
- Why does this simple JS promise return a promise?
But i just dont get it when going through my own code. I've really tried many different things programming it and deleted it, so can't show here. So I'll show what i have and what breaks my brain.
The below code is in a service file. I have imported the function in another file. I'm in React trying to use the context API & Hooks. Consider it an FYI as I don't see that relevant for the below
import firebase from "../data/firebase/config";
const fdb = firebase.firestore();
const fakeProjectMetaData = [
{
projectID: 1234,
projectName: "Testing 123",
numberOfKeywords: 2109,
scrapeFrequency: "Weekly",
lastUpdate: "2 days ago",
},
{
projectID: 4567,
projectName: "some other one",
numberOfKeywords: 10245,
scrapeFrequency: "Monthly",
lastUpdate: "Last month",
},
{
projectID: 7894,
projectName: "Creative agency version 1",
numberOfKeywords: 105,
scrapeFrequency: "Daily",
lastUpdate: "Yesterday",
},
];
// fake data is just to show the datastructure. It's not used now.
export const getAllProjects = async () => {
const allProjectData = [];
await fdb
.collection("fakeProjects")
.get()
.then((snapshot) => {
snapshot.forEach((project) => {
allProjectData.push(project.data());
return;
});
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
return allProjectData;
};
(Should I not use async await here maybe?) In this other file i invoke the function as follows:
const projectData = getAllProjects();
Now i realize this projectData is (still?) a promise that I have to process like this:
projectData.then((project) => {
console.log(project);
});
Which at least outputs an array that I expect. However changing this to the below doesn't work..
const projectArray = projectData.then((project) => {
return project;
});
console.log(projectArray);
Very curious to your answers on why this results in a promise where I expect this getAllProjects return an array of objects. What am I missing? How to get this result from firestore as an array to work with?