Home > Net >  When I get firebase data and I log it it returns the document file but when I output it it returns a
When I get firebase data and I log it it returns the document file but when I output it it returns a

Time:05-18

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 is Promise

  • The larger scope is not an async scope, so the console.log is executed right after, not waiting for the execution of what is inside getPostData

  • console.log returns a Promise

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)
  • Related