From 39f59eba268a9b1725bae9ab32efc1af740d506d Mon Sep 17 00:00:00 2001 From: Dylan Markow Date: Fri, 8 Feb 2019 07:48:00 -0800 Subject: [PATCH] fix: compact watchQueryOptions (#77) Options with undefined values shouldn't be passed to Apollo Client, otherwise they'll override any default options set on the client. This compacting behavior to remove undefined values is copied from React Apollo. --- src/__tests__/utils-test.ts | 8 ++++++++ src/useQuery.ts | 26 +++++++++++++------------- src/utils.ts | 13 +++++++++++++ 3 files changed, 34 insertions(+), 13 deletions(-) create mode 100644 src/__tests__/utils-test.ts diff --git a/src/__tests__/utils-test.ts b/src/__tests__/utils-test.ts new file mode 100644 index 0000000..dd0231d --- /dev/null +++ b/src/__tests__/utils-test.ts @@ -0,0 +1,8 @@ +import { compact } from '../utils'; + +describe('compact', () => { + it('returns a new object omitting any keys with an undefined value', () => { + const compacted = compact({ a: 'value', b: 1, c: undefined }); + expect(compacted.hasOwnProperty('c')).toBe(false); + }); +}); diff --git a/src/useQuery.ts b/src/useQuery.ts index 91e1ed6..429de02 100644 --- a/src/useQuery.ts +++ b/src/useQuery.ts @@ -18,7 +18,7 @@ import { getCachedObservableQuery, invalidateCachedObservableQuery, } from './queryCache'; -import { Omit, objToKey } from './utils'; +import { Omit, compact, objToKey } from './utils'; export interface QueryHookState extends Pick< @@ -87,17 +87,18 @@ export function useQuery( : actualCachePolicy; const watchQueryOptions: WatchQueryOptions = useMemo( - () => ({ - context, - errorPolicy, - fetchPolicy, - fetchResults, - metadata, - notifyOnNetworkStatusChange, - pollInterval, - query, - variables, - }), + () => + compact({ + context, + errorPolicy, + fetchPolicy, + fetchResults, + metadata, + notifyOnNetworkStatusChange, + pollInterval, + query, + variables, + }), [ query, @@ -112,7 +113,6 @@ export function useQuery( fetchResults, ] ); - const observableQuery = useMemo( () => getCachedObservableQuery(client, watchQueryOptions), diff --git a/src/utils.ts b/src/utils.ts index 684a5fb..2f21459 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -18,3 +18,16 @@ export function objToKey>(obj: T): T | string { export function isPromiseLike(value: unknown): value is PromiseLike { return value != null && typeof (value as PromiseLike).then === 'function'; } + +export function compact(obj: any) { + return Object.keys(obj).reduce( + (acc, key) => { + if (obj[key] !== undefined) { + acc[key] = obj[key]; + } + + return acc; + }, + {} as any + ); +}