Saccarab
Saccarab

Reputation: 1521

Firebase detach only one of the listeners on the same path

I have 2 firebase listeners on the same path. One of them fetches most recent items and the other one is query-like which gives specific user items. Both are fired on value. Is it possible to detach one of these listeners while keeping the other?

postRef = db.ref(`posts/${location}`)
postRef.orderByChild('timestamp').limitToLast(10).on("value", 
    function(snapshot) {
        dispatch({
        type: "POST_GET_POST",
        payload: snapshot.val()
    })
})

userRef = db.ref(`posts/`)
userRef.child(location).orderByChild("user").equalTo(user.uid).on("value", 
    function(snapshot) {
        dispatch({
          type: "POST_USER_POST",
          payload: snapshot.val()
    })
})

Below code will just turn both of the above listeners off.

ref = db.ref(`posts/${location}`)
ref.off

I've considered changing one of these listeners to be on child_added so I can pass the event type to ref.off() in order to select that listener. However this approach feels like going around the problem so I've wanted to know if this is possible to do in any other way.

Upvotes: 1

Views: 475

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

When you register a listener, on() returns a reference to that precise listener. If you pass that reference into off() only that listener will be removed.

So:

var query = postRef.orderByChild('timestamp').limitToLast(10);
var listener = query.on("value", 
  ...

And then:

query.off(listener);

Upvotes: 3

Related Questions