I have been working with firebase and am having trouble with this code.
The goal of the code is to get the document data with the document id.
const getPostData = async (postId) => {
const postData = await getDoc(doc(db, 'posts', postId));
console.log(postData.data()); // Returns the document data
return postData.data();
}
const postData = getPostData(id);
console.log(postData) // Returns a promise
I am extremely confused because I return the document data which when I log gives me the actual document data but when I set it as a variable it does not do the same.
CodePudding user response:
When you use a function like async
, it returns a Promise
automatically. So the problem is in logic.
What happens:
You call
getPostData
It is an
async
function, so, its return isPromise
The larger scope is not an
async
scope, so theconsole.log
is executed right after, not waiting for the execution of what is insidegetPostData
console.log
returns aPromise
Try something like:
const [postData, setPostData]= useState()
const getPostData = async (postId) => {
const postData = await getDoc(doc(db, 'posts', postId));
if (postData.exists()) {
console.log(postData.data()); // Returns the document data
setPostData(postData.data());
} else {
console.log("No posts!");
}
}
...
getPostData(id);
...
console.log(postData)
CodePudding user response:
Since you've marked getPostData
as async
it returns a Promise
and not an immediate value.
To get the value from the promise when calling getPostData
, you can either use then()
:
getPostData(id).then((postData) => {
console.log(postData)
})
Or you can use await
:
const postData = await getPostData(id);
console.log(postData)