Can Cloud Firestore onSnapshot() only trigger on changes, and not get the initial state?

后端 未结 4 1582
故里飘歌
故里飘歌 2020-12-17 20:35

The documentation says:

You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document s

4条回答
  •  借酒劲吻你
    2020-12-17 21:11

    Firestore listeners loads by their own order and the "onSnapshot" event must always execute first on initial state. But, you can handle that behavior adding a initial state variable like:

    var initState = true;
    db.collection('col').doc('id').onSnapshot(....
    

    Then you could validate inside the function the code you dont want to run when your application starts.

    var initState = true;
    db.collection('col').doc('id').onSnapshot(....
    if(!initState){ // if is not initial state
       //your code
    }
    

    and after the application starts up you must change initState to false and add a sleep/timeout function (cause it may have an unexpcted asyncronous load)

    var initState = true;
    db.collection('col').doc('id').onSnapshot(....
    if(!initState){ // if is not initial state
       //your code
    }
    
    setTimeout(function () { // cause onSnapShot executes first
       initState = false;
    }, 2000);
    

提交回复
热议问题