Home > Net >  Document in nested collection is immediately removed after reappearing adding it to the collection
Document in nested collection is immediately removed after reappearing adding it to the collection

Time:09-28

I'm using firestore and react to build my app.

This is how I add a document to the nested collection:

const handleWatch = () => {
        if(watchedList.indexOf(foundProfile.id) > -1) {
            alert('User already in list');
        } else {
            db.collection("profiles")
                .doc(myProfile.id)
                .collection("watched")
                .add({
                    watchedUserId: foundProfile.id
                })
                .then(success => props.onWatchProfile())
        }
    }

And this is how I remove it:

const handleUnwatch = (id) => {
        db.collection("profiles")
            .doc(myProfile.id)
            .collection("watched")
            .where("watchedUserId", "==", id)
            .onSnapshot(snapshot => snapshot.forEach(it => it.ref.delete()));
    }

and I'm testing the following path:

  1. Add a user with nick X
  2. Delete user with nick X
  3. Add a user with nick X
  4. Delete user with nick X

Points 1 and 2 work perfectly. During point 3 the user is added to the nested collection but immediately is deleted. In the firestore console, I see a blinking document.

What is the reason? Maybe it is problem because of firestore's cache?

CodePudding user response:

I didn't test your code but I think this is because you don't detach the listener set in handleUnwatch. Therefore the listener is immediately triggered when you create a new doc and consequently deletes this doc (.onSnapshot(snapshot => snapshot.forEach(it => it.ref.delete()));).

The listener can be cancelled by calling the function that is returned when onSnapshot is called (doc). Depending on your exact workflow you need to call this function when necessary.

For example:

const handleUnwatch = (id) => {
        const unsubscribe =  db.collection("profiles")
            .doc(myProfile.id)
            .collection("watched")
            .where("watchedUserId", "==", id)
            .onSnapshot(snapshot => {
                snapshot.forEach(it => it.ref.delete());
                unsubscribe();
            );
}

Again, the exact place where you call unsubscribe() depends on your exact functional requirements.

  • Related