React - display a firestore timestamp

后端 未结 6 2059
醉酒成梦
醉酒成梦 2020-12-18 22:38

I am trying to figure out how to display a firestore timestamp in a react app.

I have a firestore document with a field named createdAt.

I am trying to inc

6条回答
  •  借酒劲吻你
    2020-12-18 23:32

    With a document ID of a User that does have the createdAt property set, try the following:

    const docRef = db.collection("users").doc("[docID]");
    
    docRef.get().then(function(docRef) {
      if (docRef.exists) {
         console.log("user created at:", docRef.data().createdAt.toDate());
      }
    })
    

    I'ts important to call the .data() method before accessing the document's properties

    Note that if you access docRef.data().createdAt.toDate() of a user for which the createdAt propery is not set, you will get TypeError: Cannot read property 'toDate' of undefined

    So in case you have any user in your collection that has no createdAt property defined. You should implement a logic to check if the user has the createdAt property before getting it. You can do something like this:

    //This code gets all the users and logs it's creation date in the console
    docRef.get().then(function(docRef) {
      if (docRef.exists && docRef.data().createdAt) {
          console.log("User created at:", docRef.data().createdAt.toDate());
      }
    })
    

提交回复
热议问题