Reputation: 1087
I use Firestore in React. And this application saves created_at
datetime as Timestamp object to Firestore like below. use firebase.firestore.FieldValue.serverTimestamp()
.
export function createComment(uid, values, count) {
return dispatch => {
commentsRef
.add({
uid: uid,
content: values.content,
created_at: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function() {
roomsRef
.doc(uid)
.update({
comment_count: Number(count) + 1
})
.then(() => {
dispatch({ type: CREATE_COMMENT });
});
});
};
}
But the error occurs when I tried to display created_at
Timestamp.
// Fetch comments
export function fetchComments(uid) {
return dispatch => {
commentsRef
.where("uid", "==", uid)
.get()
.then(snapshot => {
const comments = snapshot.docs.map(doc => {
return {
const timstamp = doc.data().created_at.toDate();
// error occurs
...doc.data(),
id: doc.id,
timestamp: timestamp
};
});
return comments;
})
.then(comments => {
dispatch({ type: FETCH_COMMENTS, payload: comments });
});
};
}
error:
TypeError: Cannot read property 'toDate' of undefined
Timestamp is successfully fetched though.
Upvotes: 2
Views: 4050
Reputation: 7324
created_At
is an object, as you have clearly shown in the log. If you want to convert it to a date then pick one of the fields. So created_at.nanoseconds
will give you a timestamp you can convert.
I'm not sure what toDate()
is, that's not a native js method, are you referring moment js? If you want to convert a timestamp into a date you should try new Date(created_at.nanoseconds)
Upvotes: 2