firestore onSnapshot executing twice

后端 未结 2 1673
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-02 21:41

My firestore onSnapshot() function is being called twice.

let user = firebase.firestore().collection(\'users\').doc(userID).onSnapshot
({                             


        
相关标签:
2条回答
  • 2021-01-02 22:10

    If you need a one time response, use the .get() method for a promise.

    firebase.firestore().collection('users').doc(userID).get().then(snap => {
      this.userArray = [...this.userArray, snap.doc);
    });
    

    However, I suggest using AngularFire (totally biased since I maintain the library). It makes handling common Angular + Firebase tasks much easier.

    0 讨论(0)
  • 2021-01-02 22:16

    I don't know if this is related to your question. If one is using

    firebase.firestore.FieldValue.serverTimestamp()
    

    to give a document a timestamp, then onSnaphot will fire twice. This seem to be because when you add a new document to your database onSnapshot will fire, but the serverTimestamp has not run yet. After a few milliseconds serverTimestamp will run and update you document => onSnapshot will fire again.

    I would like to add a small delay before onSnapshot fires (say 0,5s or so), but I couldn't find the way to do this.

    You can also make a server side function for onCreate event, I believe that would solve your problem. Maybe your userArray.push-action would be more suitable to execute in server side.

    0 讨论(0)
提交回复
热议问题