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

后端 未结 4 1586
故里飘歌
故里飘歌 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:21

    After reading the first and second solution, I have made a solution that seems to work. First you initialize a variable to true and inside the onSnapshot() method you check if this variable is true, if it is, you change it to false, and on else you write your retrieving data algorithm. Something like this:

    var initState = true;
    
    let observer = records.onSnapshot(docSnapshot => {
    
        console.log(`Received doc snapshot`);
    
        if (initState) {
            initState = false;
        } else {
            if (!docSnapshot.docChanges().empty) {     
                docSnapshot.docChanges().forEach(function (change) {
                   //Write here wahtever you want
    
                });
            }
        }
    
    }, err => {
        console.log(`Encountered error: ${err}`);
    });
    

提交回复
热议问题