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.
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();
}, [])
So if you look at this we're subscribing to event when the modal is not visible and store that in a variable called unsubscribe . In the clean up method of useEffect , we just call the unsubscribe to cancel our graphql subscription. Also, remember to add modalVisible as another dependency to our hook.
This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. The instruction is pretty clear and straightforward, "cancel all subscriptions and asynchronous tasks in a useEffect cleanup function".
Open your favorite browser and navigate to http://localhost:3000/graphql, you will see the playground UI appear, so run the subscription. The playground will start listening to event updates from the GraphQL server. Create a second tab and load http://localhost:3000/graphql on it.
Subscriptions are similar to queries in that they specify a set of fields to be delivered to the client, but instead of immediately returning a single answer, a result is sent every time a particular event happens on the server.
SubscribeToMore returns the unsubscribe function, so your code is correct.
https://github.com/apollographql/apollo-client/issues/5245
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With