Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to unsubscribe with useQuery and subscribeToMore

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();
}, [])
like image 652
Chance Smith Avatar asked Mar 03 '20 21:03

Chance Smith


People also ask

How do I cancel my subscription to GraphQL?

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.

Where you would unsubscribe from a subscription in useEffect?

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".

How do I use subscriptions in GraphQL?

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.

What are subscriptions react?

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.


1 Answers

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

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

like image 122
Maapteh Avatar answered Sep 28 '22 07:09

Maapteh