IjzerenHein / firestorter

Use Google Firestore in React with zero effort, using MobX 🤘
http://firestorter.com
MIT License
378 stars 50 forks source link

Stop listener #72

Closed RWOverdijk closed 5 years ago

RWOverdijk commented 5 years ago

First off:

Now, time to ask a dumb question.

Currently I'm doing the stuff that firestorter does myself, manually. I want to move over, because this module looks a lot easier on the psyche.

One thing I can't seem to find in the docs is how to stop listening for changes. I do this when the user's auth state changes because .where() has a filter on it like so:

const collection = new Collection('chats', {
  query: (ref: any) => ref.where('members', 'array-contains', uid)
});

But when the user logs out, there won't be a uid anymore and for obvious reasons this should stop listening for changes.

Question 1: If I use docs in my render, will firestorter take care of this already by disposing of the ref and stopping any onSnapshot listeners? Question 2, maybe: If not, how can I re-initialize the collection when the auth state changes doing this myself?

damonmaria commented 5 years ago

If you access the uid through an observable reference inside the query function then the query will automatically update when the uid changes. And in the situation where there is no user then from the query function you can return null which will result in an empty collection. But I've just noticed that returning null isn't in the documentation.

damonmaria commented 5 years ago

FYI I've just done a PR documenting the null return from Collection.query: #75

IjzerenHein commented 5 years ago

That is correct, by returning null from the query function, the Collection will automatically stop listening. The uid itself needs to be an observable though. Something like this should work:

const uid = observable.box(undefined);
firebase.auth().onAuthStateChanged(firebaseUser => {
  runInAction(() => {
    uid.set(firebaseUser ? firebaseUser.uid : null);
  });
});

const collection = new Collection('chats', {
  query: (ref: any) => uid ? ref.where('members', 'array-contains', uid) : null
});

FYI I've just done a PR documenting the null return from Collection.query: #75

@damonmaria Awesome, thanks for documenting that better! 🙏

IjzerenHein commented 5 years ago

Additionally, what you can do is set the debug option on the Collection. When enabled it will log when the it starts and stops listening to the console.

RWOverdijk commented 5 years ago

Additionally, what you can do is set the debug option on the Collection. When enabled it will log when the it starts and stops listening to the console.

That's cool. I'll use that for sure. Consider me informed! :)