Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix useSubscription executes skipped subscription if input changes #9299

Merged
merged 2 commits into from
Jan 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/react/hooks/__tests__/useSubscription.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -127,19 +127,27 @@ describe('useSubscription Hook', () => {
}
`;

const onSetup = jest.fn();
const link = new MockSubscriptionLink();
link.onSetup(onSetup);
const client = new ApolloClient({
link,
cache: new Cache({ addTypename: false })
});

const onSubscriptionData = jest.fn();
const { result, unmount, waitForNextUpdate } = renderHook(
() => useSubscription(subscription, {
onSubscriptionData,
const { result, unmount, waitForNextUpdate, rerender } = renderHook(
({ variables }) => useSubscription(subscription, {
variables,
skip: true,
onSubscriptionData,
}),
{
initialProps: {
variables: {
foo: 'bar'
}
},
wrapper: ({ children }) => (
<ApolloProvider client={client}>
{children}
Expand All @@ -151,11 +159,14 @@ describe('useSubscription Hook', () => {
expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(undefined);
expect(result.current.data).toBe(undefined);

rerender({ variables: { foo: 'bar2' }});
await expect(waitForNextUpdate({ timeout: 20 }))
.rejects.toThrow('Timed out');
unmount();

expect(onSetup).toHaveBeenCalledTimes(0);
expect(onSubscriptionData).toHaveBeenCalledTimes(0);
unmount();
});

it('should create a subscription after skip has changed from true to a falsy value', async () => {
Expand Down
18 changes: 10 additions & 8 deletions src/react/hooks/useSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,16 @@ export function useSubscription<TData = any, TVariables = OperationVariables>(
shouldResubscribe = !!shouldResubscribe(options!);
}

if (options?.skip && !options?.skip !== !ref.current.options?.skip) {
setResult({
loading: false,
data: void 0,
error: void 0,
variables: options?.variables,
});
setObservable(null);
if (options?.skip) {
if (!options?.skip !== !ref.current.options?.skip) {
setResult({
loading: false,
data: void 0,
error: void 0,
variables: options?.variables,
});
setObservable(null);
}
benjamn marked this conversation as resolved.
Show resolved Hide resolved
} else if (
shouldResubscribe !== false && (
client !== ref.current.client ||
Expand Down