How to remove firebase database listener when ref path is no longer available

Viewed 4935

I'm using firebase in a react native app and I have a listener similar to this:

firebase.database().ref('users/'+uid+'/items').on('value', function(snapshot){
    ....
})

What I'm trying to do is to remove that listener when the user logs out. I know that I can do it using off() like:

firebase.database().ref('users/'+uid+'/items').off('value', function(snapshot){
    ....
})

But once the user logs out I no longer have access to the user id. So how do I remove the listener?

1 Answers

You'll need to retain the path on which you've attached the listener so that you can call off() on it. One way to do this would be:

mUserRef = firebase.database().ref('users/'+uid+'/items');
mUserRef.on('value', function(snapshot){
    ....
})

And then later:

mUserRef.off('value');
Related