You mention experiencing the issue of receiving "undefined as output" when in reality, you are not entirely getting undefined.
For the initial console.log(), you are obtaining an object value, whereas for the subsequent console.log(), you are indeed receiving undefined
as the output.
The reason behind this discrepancy is that the second console.log() aims to display the value of DocumentDate
, which, based on your invocation of setDocumentDate()
, appears to be a state variable.
It is crucial to understand that the 'set state function' in NextJS/React operates asynchronously. Upon calling it, JavaScript places the task in the asynchronous queue and proceeds with executing the subsequent line of code. Consequently, the state variable's value will not update until after completing the component's current rendering process.
Hence, setDocument(docSnap.data())
will not immediately assign a value to Document
. As a result, invoking
setDocumentDate(Document.dateCreated)
will yield
undefined
, given that
Document
remains devoid of a value. Moreover, even if there were a value within
Document
, the call to
console.log(DocumentDate)
would still display
undefined
since
DocumentDate
lacks any assigned value at that moment.