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