From 8670f7f60c4cffa977fa39b5bbfcc4b210510a76 Mon Sep 17 00:00:00 2001 From: Daniel K Date: Wed, 27 Feb 2019 08:27:05 +0100 Subject: [PATCH] feat(useSubscription): add skip option (#98) --- README.md | 3 ++ src/__tests__/useSubscription-test.tsx | 38 +++++++++++++++++++++++++- src/useSubscription.ts | 4 +++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 00b01d7..c6eea8b 100644 --- a/README.md +++ b/README.md @@ -275,6 +275,9 @@ const { data, error, loading } = useSubscription(MY_SUBSCRIPTION, { }); ``` +In some cases you might want to subscribe only after you have all the information available, eg. only when user has selected necessary filters. Since hooks cannot be used conditionally, it would lead to unnecessary complicated patterns. + +Instead, you can use the `skip` option which turns the subsciption dormant until toggled again. It will also unsubscribe if there was any previous subscription active and throw away previous result. ## useApolloClient diff --git a/src/__tests__/useSubscription-test.tsx b/src/__tests__/useSubscription-test.tsx index 1feba3c..e1a0b42 100644 --- a/src/__tests__/useSubscription-test.tsx +++ b/src/__tests__/useSubscription-test.tsx @@ -3,7 +3,7 @@ import { Operation } from 'apollo-link'; import { MockSubscriptionLink } from 'apollo-link-mock'; import gql from 'graphql-tag'; import React from 'react'; -import { cleanup, render } from 'react-testing-library'; +import { act, cleanup, render } from 'react-testing-library'; import { ApolloProvider, useSubscription } from '..'; import createClient from '../__testutils__/createClient'; @@ -327,3 +327,39 @@ it('should re-subscription if variables have changed', async () => { expect(count).toBe(5); }); + +it('should not subscribe if skip option is enabled', async () => { + const variables = { completed: true }; + + class MockSubscriptionLinkOverride extends MockSubscriptionLink { + request(req: Operation) { + expect(req.variables).toEqual(variables); + return super.request(req); + } + } + + const link = new MockSubscriptionLinkOverride(); + + const client = createClient({ link }); + + const Component = () => { + const { data, loading, error } = useSubscription( + FILTERED_TASKS_SUBSCRIPTION, + { variables, skip: true } + ); + expect(loading).toBe(true); + expect(error).toBeUndefined(); + expect(data).toBeUndefined(); + return null; + }; + + render( + + + + ); + + act(() => { + link.simulateResult(complitedResults[0]); + }); +}); diff --git a/src/useSubscription.ts b/src/useSubscription.ts index 4e9ed35..f9cf341 100644 --- a/src/useSubscription.ts +++ b/src/useSubscription.ts @@ -22,6 +22,7 @@ export interface OnSubscriptionDataOptions { export interface SubscriptionHookOptions extends Omit, 'query'> { + skip?: boolean; onSubscriptionData?: OnSubscriptionData; } @@ -57,6 +58,9 @@ export function useSubscription( useEffect( () => { + if (options.skip === true) { + return; + } const subscription = client .subscribe({ ...options,