how to unsubscribe with useQuery and subscribeToMore
Asked Answered
I

2

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();
}, [])
Inward answered 3/3, 2020 at 21:2 Comment(0)
B
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.

Bing answered 3/3, 2020 at 21:14 Comment(1)
So, I can ditch this? return () => unsubscribe();Inward
I
2

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

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

Ivie answered 11/10, 2020 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.