1

I want to unsubscribe the fetch when a component unmounts.

I fetch like this:

const snapshot = await db.collection(`users/user/messages`);

With a slow internet this may takes a while, and before fetching finish, component may unmount.

So how to Unsubscribe or cancel in the background when component gets unmounted?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Muhammad
  • 2,572
  • 4
  • 24
  • 46
  • you can unsubscribe onSnapshot event in react lifecycle hooks called componentWillUnmount, here the link of firebase detach listener: https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener – Ravi Khunt Jan 30 '20 at 05:17
  • Thank you, If I use `onSnapshot` instead of `get` Can I get the same result and the same performance ? – Muhammad Jan 30 '20 at 06:10

1 Answers1

3

I'm assuming your code actually has a .get() a the end of the line in order to actually execute the query.

Firestore operations that return promises can't be canceled (like nearly all APIs that return promises). The promise will eventually resolve or reject. You don't have to do anything with any data that you get as a result, but the SDK will definitely wait for the query to complete and fetch all the data.

If this is going to cause a problem for your app, consider fetching less data by paginating through the results and only loading documents when they are about to become visible. This is a lot more work, but it might save you time and money for large data sets.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thank you, If I use `onSnapshot` instead of `get` Can I get the same result and the same performance ? – Muhammad Jan 30 '20 at 06:09
  • 1
    It's not really any faster. It just listens for changes continually over time, until you manually remove the listener. Removing the listener doesn't cancel any document transfers in progress. If this behavior not exactly what you want, then don't use it. – Doug Stevenson Jan 30 '20 at 06:20