0

I use React + Firestore(Firebase). And the application logs datetime created at every time the post is created. And I use firebbase.firestore.FieldValue.serverTimestamp().

Create code:

export function updateProfile(uid, values) {
  return dispatch => {
    databaseRef
      .doc(uid)
      .update({
        name: values.name,
        created_at: firebase.firestore.FieldValue.serverTimestamp()
      })
      .then(() => {
        dispatch({ type: CREATE_ITEM });
      });
  };
}

Fetch code:

// Fetch profile
export function fetchItem(id) {
  return dispatch => {
      databaseRef
        .doc(id)
        .get()
        .then(doc => {
          dispatch({ type: FETCH_ITEM, payload: doc.data() });
        });
  };
}

But datetime objects in Firestore are rendered. So it's not simple to display in the view. I try to like {item.created_at}. But the error occurs.

The error:

Error: Objects are not valid as a React child (found: object with keys {seconds, nanoseconds}). If you meant to render a collection of children, use an array instead.

My final goal is to display how long time ago the post is created like 2 hours ago, 1 days ago. But my first step is to display this.

Additional

I tried toDate().

<p>{item.created_at.toDate()}</p>

=> TypeError: Cannot read property 'toDate' of undefined

I tried Timestamp.toDate().

<p>{item.created_at.Timestamp.toDate()}</p>

=> TypeError: Cannot read property 'Timestamp' of undefined
k10a
  • 555
  • 4
  • 14
  • Hi, you should use the `toDate` method to convert a Timestamp to a JavaScript Date object, as detailed in the [doc](https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp.html#todate). – Renaud Tarnec Feb 03 '20 at 08:26
  • I did try but `Cannot read property 'toDate' of undefined` error occurs. – k10a Feb 03 '20 at 08:30
  • Note that `toDate()` is a method, so you should call it as `timestamp.toDate()`. But the error you are receiving shows that your value of timestamp is undefined. You may check if you get a correct value. – Renaud Tarnec Feb 03 '20 at 09:09
  • `Timestampseconds: 1580727807nanoseconds: 999000000` I can get correct timestamp... – k10a Feb 03 '20 at 11:04
  • Pls share your entire code, in order for us to understand how you get the is value. – Renaud Tarnec Feb 03 '20 at 11:17
  • Thank you so much for your help. I have added in details. – k10a Feb 03 '20 at 22:31

0 Answers0