Why ``firebase.firestore.FieldValue.serverTimestamp()`` generates firestore timestamp after some delay?

Viewed 14

I am working on a chat application. When I send my chat message I need to make some some transactions.

Here is the code:

const handleSubmit = (e) => {
    e.preventDefault();

    document.getElementById('chat').value = '';

    if (message.length > 0) {

      let mergedId = loggedUserId + toBeContactedUserId;

      let loggedUserRef = db.collection('users').doc(loggedUserId);
      let toBeContactedUserRef = db.collection('users').doc(toBeContactedUserId);
      let messageDbRef = db.collection('messages').doc();

      db.runTransaction((transaction) => {

        const p1 = transaction.get(loggedUserRef)
          .then(userDoc => {
             //Some operation occurs
          })

        const p2 = transaction.get(toBeContactedUserRef)
          .then(userDoc => {
            //Some operation occurs
          })

        const p3 = transaction.get(messageDbRef)
          .then(msgDoc => {
            messageDbRef.set({
              from: loggedUserId,
              to: toBeContactedUserId,
              content: message,
              reaction: false,
              image: false,
              file: false,
              filename: '',
              seen: false,
              searchId: mergedId,
              time: firebase.firestore.FieldValue.serverTimestamp()
            })
          })

        return Promise.all([p1, p2, p3]);

      })
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        })
    }
  }

The third transaction is where the new message is stored in the database. Here I am using firebase.firestore.FieldValue.serverTimestamp() to generate firestore timestamp object.

In a normal run the message added should be displayed on the screen(as I am using real-time firestore updation). Also I am using moment(msgTime.toDate()).format('MM-DD-YYYY') to show the date and time when the message was sent.[msgTime is the firestore timestamp of every single message]

But in real as soon as I press on the send button I get the error as Cannot read properties of null (reading 'toDate')

I tried to console through the message array through which I am looping in the jsx.

Here is what I see:

enter image description here

The new message generated is showing time as null. But when I reload the page everything works well.

Please guide why there is a such a delay that is causing my application to break. Let me know if more information is required.

0 Answers
Related