Aziz Badar
Aziz Badar

Reputation: 3

While Updating Firestore Data timestamp is null

I have a realtime listener for orders when I accept order there is one field updates named "status" and another field is added named "datetime_accepted"

Here is Listener for monitoring document change

db.collection('ORDERS').where('status', '==', 'a').orderBy('datetime_accepted')
  .onSnapshot(querySnapshot => {
    querySnapshot.docChanges().forEach(change => {
      if (change.type === 'added') {
        var id = change.doc.id
        var snapJSON = JSON.stringify(change.doc.data());
        var orderOBJ = JSON.parse(snapJSON);
        orderOBJ.oid = id;
        var confirm_datetime = new Date(orderOBJ.datetime_accepted.seconds*1000).toLocaleString();

This is a Separate Function which I am running to update the fields

db.collection("ORDERS").doc(id).update({
    "datetime_accepted": firebase.firestore.FieldValue.serverTimestamp(),
    "status": "a"
})

When Status of order is changed the error happened but after refreshing the timestamp works fine again This Problem is only in realtime updation in timestamp

enter image description here

Upvotes: 0

Views: 309

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

This is the expected behavior. There are two things to keep in mind:

  1. Server timestamps don't have an actual value until the document actually reaches the server
  2. Firestore document listeners will trigger immediately when a document is changed, before the document reaches the server.

This means that your listener is receiving the update before it reaches the server, and that snapshot is not going to have a timestamp in it.

Your code will need to check for this specific case by handling the undefined timestamp value. Read more about how server timestamps work.

Upvotes: 2

Related Questions