fetching data from Firestore but the problem is in date field
dateCreated : Timestamp nanoseconds : 518000000 seconds : 1722162236 [[Prototype]] : Object dislikes : 1
const docSnap = await getDoc(docref);
if (docSnap.exists()) {
console.log(docSnap.data());
setDocument(docSnap.data());
setDocumentDate(Document.dateCreated);
console.log(DocumentDate);
} else {
console.log("Document does not exist");
}
undefined
I have no idea why this is happening
2
Answers
You say that you are "getting undefined as output" but you aren’t.
You are getting an object value for the first console.log() and you are getting
undefined
for the second console.log().The second console.log() is attempting to render the value of
DocumentDate
which, assuming from the fact that you callsetDocumentDate()
, is a state variable.You want to realize that the "set state function" in NextJS/React is an asynchronous function. When you call it, JS puts the work to be done on the "asynch queue" and continues to your next line of code. The value of the state variable will not be updated until AFTER the current rendering of the component completes.
So
setDocument(docSnap.data())
will not set a value ofDocument
right away.setDocumentDate(Document.dateCreated)
will getundefined
sinceDocument
does not yet have a value, and even if there was a value inDocument
the call toconsole.log(DocumentDate)
would renderundefined
because there is no value set inDocumentDate
yet.If your document has a
dateCreated
field that you want to print, you access that withdocSnap.data().dateCreated
. So