Skip to content

Commit

Permalink
fix: compact watchQueryOptions (#77)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dmarkow authored and trojanowski committed Feb 8, 2019
1 parent 5d60caa commit 39f59eb
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 13 deletions.
8 changes: 8 additions & 0 deletions src/__tests__/utils-test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
26 changes: 13 additions & 13 deletions src/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
getCachedObservableQuery,
invalidateCachedObservableQuery,
} from './queryCache';
import { Omit, objToKey } from './utils';
import { Omit, compact, objToKey } from './utils';

export interface QueryHookState<TData>
extends Pick<
Expand Down Expand Up @@ -87,17 +87,18 @@ export function useQuery<TData = any, TVariables = OperationVariables>(
: actualCachePolicy;

const watchQueryOptions: WatchQueryOptions<TVariables> = useMemo(
() => ({
context,
errorPolicy,
fetchPolicy,
fetchResults,
metadata,
notifyOnNetworkStatusChange,
pollInterval,
query,
variables,
}),
() =>
compact({
context,
errorPolicy,
fetchPolicy,
fetchResults,
metadata,
notifyOnNetworkStatusChange,
pollInterval,
query,
variables,
}),
[
query,

Expand All @@ -112,7 +113,6 @@ export function useQuery<TData = any, TVariables = OperationVariables>(
fetchResults,
]
);

const observableQuery = useMemo(
() =>
getCachedObservableQuery<TData, TVariables>(client, watchQueryOptions),
Expand Down
13 changes: 13 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,16 @@ export function objToKey<T extends Record<string, any>>(obj: T): T | string {
export function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
return value != null && typeof (value as PromiseLike<T>).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
);
}

0 comments on commit 39f59eb

Please sign in to comment.