How to unsubscribe before resubscribing when subscription variables change? #385
-
I am using useEffect to detect changes to GraphGL subscription variables where we subscribe to new subscriptions when the user changes filters or the offset/limit changes. I am having trouble unsubscribing from the previous subscription before subscribing to the new one. Currently when the variables change, there are several open sockets each time the variables change rather than there just being one open socket at a time. We are using Hasura and TanStack (React Query) and the onNext handler invalidates the cache in the useInfiniteQuery when the new data comes in. Here's what the useEffect looks like. How can I ensure that the current socket is closed/unsubscribed before subscribing to the new one? Here is an example of my code. Appreciate the help!!
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You're probably recreating the client every time the useEffect hook gets called. In I always recommend splitting the hooks, try something like this: const client = useMemo(
() =>
createClient({
url: 'GRAPH_QL_URL',
connectionParams() {
return {
headers: {
key: 'token',
},
}
},
}),
[],
)
useEffect(() => {
const onNext = (data) => {
// Handling onNext events
}
const onError = (err) => {
// Handle errors
}
const onComplete = () => {
// Subscription completed
}
return client.subscribe(
{
variables: {
where: where,
order_by: orderBy,
offset: 0,
limit: totalFetched,
},
query: subscription,
},
{
next: onNext,
error: onError,
complete: onComplete,
},
)
}, [client, where, orderBy, slug, totalFetched]) |
Beta Was this translation helpful? Give feedback.
You're probably recreating the client every time the useEffect hook gets called. In
graphql-ws
1 client means 1 socket, a single client will never have multiple open sockets.I always recommend splitting the hooks, try something like this: