13

Another post shared an example of how to unsubscribe, where the Apollo docs don't. The Apollo docs do mention what subscribeToMore returns...

subscribeToMore: A function that sets up a subscription. subscribeToMore returns a function that you can use to unsubscribe.

This does give a hint. It would help to see an example.

the question

Using @apollo/react-hooks, inside of a useEffect() and returning the results of the subscribeToMore, is this the way to unsubscribe on a component unmount?

const { data, error, loading, subscribeToMore } = useQuery(GET_DATA)

useEffect(() => {
    const unsubscribe = subscribeToMore(/*...*/)
    return () => unsubscribe();
}, [])
Chance Smith
  • 1,211
  • 1
  • 15
  • 32

2 Answers2

5

Any associated subscriptions should be unsubscribed for you when the component unmounts. You shouldn't have to manually manage it unless you want to unsubscribe before then.

You can see the subscription being tracked when subscribeToMore is called here and then unsubscribed when the query is being cleaned up here.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
2

SubscribeToMore returns the unsubscribe function, so your code is correct.

https://github.com/apollographql/apollo-client/issues/5245

Maapteh
  • 136
  • 4