skip to Main Content

fetching data from Firestore but the problem is in date field

getting the data

dateCreated : Timestamp nanoseconds : 518000000 seconds : 1722162236 [[Prototype]] : Object dislikes : 1

trying to print the date

    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");
    }

getting undefined as output

undefined

I have no idea why this is happening

2

Answers


  1. 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 call setDocumentDate(), 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 of Document right away. setDocumentDate(Document.dateCreated) will get undefined since Document does not yet have a value, and even if there was a value in Document the call to console.log(DocumentDate) would render undefined because there is no value set in DocumentDate yet.

    Login or Signup to reply.
  2. If your document has a dateCreated field that you want to print, you access that with docSnap.data().dateCreated. So

    setDocumentDate(docSnap.data().dateCreated);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search