Search code examples
angularfirebasegoogle-cloud-firestorelistenersnapshot

Trigger change type only once when observing Firestore listeners


There is a popout triggered based on a user marking an action as complete. But if the user checks off many items and doesn’t refresh the page, all of the previous popouts continue to pop up and they have to x out of each one of them each time.

Not sure why this is, and I have an unsubscribe.

    async checkProgress(){
        debugger
      if (this.Origin == 'SGBA') {
       if (this.data?.action==="update" && this.status == 'Complete') {
        //Gets modified document data to pass into progress popout component
        let newData;
        let q = await this.busiAssessmentService.readOverallData2(this.UID);
        const unsubscribe = await onSnapshot(q, (snapshot) => {
       let  changes = snapshot.docChanges()
       console.log(changes.length)
       changes.forEach((change) => { 
            console.log(change.type)
            console.log("change.type")
          if (change.type === "modified") {
              newData = change.doc.data();
              console.log("Modified doc: ", change.doc.data());
               this.openBox(newData, this.inputSource, this.Category)
              return newData;
              }
            });
          },(error) => {
              console.log(error)
           });
           if (newData !== undefined){
            unsubscribe();
           }
      }
     }
    }


Solution

  • You were unsubscribing onSnapshot unsubscription at wrong place instead of unsubscribing at the end unsubscribe just after this.openBox(newData, this.inputSource, this.Category); line.

    Updated code :

    async checkProgress(){
      if (this.Origin == 'SGBA') {
        if (this.data?.action==="update" && this.status == 'Complete') {
          //Gets modified document data to pass into openBox
          let newData;
          let q = await this.busiAssessmentService.readOverallData2(this.UID);
          const unsubscribe = await onSnapshot(q, (snapshot) => {
            let changes = snapshot.docChanges();
            console.log(changes.length);
            changes.forEach((change) => { 
              console.log(change.type);
              console.log("change.type");
              if (change.type === "modified") {
                newData = change.doc.data();
                console.log("Modified doc: ", change.doc.data());
                this.openBox(newData, this.inputSource, this.Category);
                unsubscribe(); // unsubscribe from the listener after the first popout
              }
            });
          }, (error) => {
            console.log(error);
          });
        }
      }
    }