0

I am using firestore and react-native-gifted-chat, I am trying to get all the chat messages from firestore to the chat. However, gifted chat does not support displaying firebase timestamp. It will show invalid Date. Therefore, I m trying to convert all the date object.

async _getMessage() {
  const messColRef = db.collection('Message').doc(this.state.roomName).collection('message').orderBy('createdAt', 'desc').limit(9)
  const initialQuery = messColRef
  const documentSnapshots = await initialQuery.get()
  const documentData = documentSnapshots.docs.map(document => ({
    id: document.id, ...document.data()
  }));
  const lastVisible = documentData[documentData.length - 1]

  const finalData = _.forEach(documentData['createdAt'], (item) => {
    return item.toDate()
  });
  console.log(documentData)
}

and it is how my data look like:

{
  "_id": "f0feb0b6-c0f9-4735-a93d-4297872a4840",
    "createdAt": Timestamp {
    "nanoseconds": 382000000,
      "seconds": 1568995812,
 },
  "id": "Uw6PNNsf7aqWrxcgSDSi",
    "text": "Hi",
      "user": {
    "_id": "V8h2iSllhPXSr8sTGP0yHiaYZwx1",
      "avatar": "https://firebasestorage.googleapis.com/v0/b/exit-3684f.appspot.com/o/add- 
    user.png ? alt = media & token=395c8beb - 47a3 - 4ae6 - a0a1 - fe901e7ad42f",
    "name": "This is the username",
 },
},
{
  "_id": "cc298d96-f19a-4ec7-bdf7-3767d900a364",
    "createdAt": Timestamp {
    "nanoseconds": 373000000,
      "seconds": 1568995733,
 },
  "id": "WzbOA52Y3qukvPUIXRLB",
    "text": "hello",
      "user": {
    "_id": "V8h2iSllhPXSr8sTGP0yHiaYZwx1",
      "avatar": "https://firebasestorage.googleapis.com/v0/b/exit-3684f.appspot.com/o/add- 
    user.png ? alt = media & token=395c8beb - 47a3 - 4ae6 - a0a1 - fe901e7ad42f",
    "name": "This is the username",
    },
},

so my goal is to convert all the createdAt to js time date

Kishan Bharda
  • 5,446
  • 3
  • 30
  • 57
Rachellllls
  • 15
  • 1
  • 4
  • Possible duplicate of [How do I convert a Firestore date/Timestamp to a JS Date()?](https://stackoverflow.com/questions/52247445/how-do-i-convert-a-firestore-date-timestamp-to-a-js-date) – Spatz Sep 20 '19 at 18:51

2 Answers2

0

Sorry for not explore deeply, after checking @Spatz comments I figure out how to do it

documentData.forEach(a => {
  var date = a.createdAt.toDate()
  data.push({
    _id: a._id,
    createdAt: date,
    id: a.id,
    text: a.text,
    user: a.user
  })
})
Kishan Bharda
  • 5,446
  • 3
  • 30
  • 57
Rachellllls
  • 15
  • 1
  • 4
0

Use renderTime prop of gifted chat and pass a function which converts the time and return that time in a string.