Search code examples
javascriptfirebasegoogle-cloud-firestorerxjsangularfire

SnapshotChanges subscription doesn't detect final deletion of sub-collection item


I have the following code to retrieve some user information from Cloud Firestore - it grabs the list of challenges a user is part of from a subcollection on their user document and then uses those ids to collect the full challenge information from the top level challenge document.

When I delete a challenge I remove it from the main challenges document and then remove the id reference in each users challenges subcollection. The UI updates nicely for each delete as snapshotchanges is an active subscription, until I delete the final one. The final one deletes from the database but stays in the UI until I refresh or make a new challenge.

My theory is that becuase deleting the last document in the challenges subcollection also deletes the subcollection this means snapshotChanges doesn't run as there is no longer a collection in the database to monitor the changes on.

Any thoughts on how to workaround this would be great.

  getChallenges() {
    return this.getCurrentUserId().pipe(switchMap(userId => {
      return this.db.collection(`users/${userId}/challenges`).snapshotChanges().pipe(
        map(actions => actions.map(a => {
          const data = a.payload.doc.data();
          console.log('in get challenges: ', data);
          const user_challenge_key = a.payload.doc.id;
          return this.getOneChallenge(data['id'], user_challenge_key);
        }))
      );
    }));
  }

  getOneChallenge(id, user_challenge_key = null): Observable<Challenge> {
    return this.db.doc(`challenges/${id}`).snapshotChanges().pipe(
      take(1),
      map(changes => {
        const data = new Challenge(changes.payload.data());
        const challengeId = changes.payload.id;
        data.user_challenge_key = user_challenge_key;
        data.id = id;
        console.log('in get One challenge: ', data);
        return data;
      })
    );
  }

Solution

  • Maybe maintain a dummy document in order to keep the sub-collection

    For example, validate if you going to delete the last element of that sub-collection add the dummy and later delete the last element

    for the first insertion check if the dummy object is the only document, after that add your first entry and delete the dummy

    I found a similar question with similar approach on the Firestore's Google Group