Skip to content

Commit

Permalink
useSubscribe on use effect (#111)
Browse files Browse the repository at this point in the history
  • Loading branch information
PabloSzx authored Sep 9, 2023
1 parent c68e8ac commit 492118a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/yellow-peas-study.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@soundxyz/graphql-react-ws': patch
---

useSubscribe on use effect
14 changes: 5 additions & 9 deletions packages/graphql-react-ws/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ClientOptions, createClient, ExecutionResult, SubscribePayload } from 'graphql-ws';
import { useEffect, useMemo } from 'react';
import { useEffect } from 'react';
import { proxy, ref } from 'valtio';

import { useProxySnapshot, useStableCallback, useStableValue } from './utils';
Expand Down Expand Up @@ -335,11 +335,10 @@ export function GraphQLReactWS<ConnectionInitPayload extends Record<string, unkn

const stableVariables = useStableValue(variables);

const subscription = useMemo(() => {
if (typeof window === 'undefined' || stableVariables === false || enabled === false)
return null;
useEffect(() => {
if (typeof window === 'undefined' || stableVariables === false || enabled === false) return;

return subscribe(
const subscription = subscribe(
{
query,
// Can't verify the conditional types around optional variables
Expand Down Expand Up @@ -379,18 +378,15 @@ export function GraphQLReactWS<ConnectionInitPayload extends Record<string, unkn
}
},
);
}, [stableVariables, enabled, query]);

useEffect(() => {
if (!subscription) return;

return () => {
subscription.abortController.abort();
};
}, [subscription]);
}, [stableVariables, enabled, query]);

return {
subscription,
data,
error,
store,
Expand Down

0 comments on commit 492118a

Please sign in to comment.