Skip to content

Commit 39f59eb

Browse files
dmarkowtrojanowski
authored andcommitted
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.
1 parent 5d60caa commit 39f59eb

File tree

3 files changed

+34
-13
lines changed

3 files changed

+34
-13
lines changed

src/__tests__/utils-test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { compact } from '../utils';
2+
3+
describe('compact', () => {
4+
it('returns a new object omitting any keys with an undefined value', () => {
5+
const compacted = compact({ a: 'value', b: 1, c: undefined });
6+
expect(compacted.hasOwnProperty('c')).toBe(false);
7+
});
8+
});

src/useQuery.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
getCachedObservableQuery,
1919
invalidateCachedObservableQuery,
2020
} from './queryCache';
21-
import { Omit, objToKey } from './utils';
21+
import { Omit, compact, objToKey } from './utils';
2222

2323
export interface QueryHookState<TData>
2424
extends Pick<
@@ -87,17 +87,18 @@ export function useQuery<TData = any, TVariables = OperationVariables>(
8787
: actualCachePolicy;
8888

8989
const watchQueryOptions: WatchQueryOptions<TVariables> = useMemo(
90-
() => ({
91-
context,
92-
errorPolicy,
93-
fetchPolicy,
94-
fetchResults,
95-
metadata,
96-
notifyOnNetworkStatusChange,
97-
pollInterval,
98-
query,
99-
variables,
100-
}),
90+
() =>
91+
compact({
92+
context,
93+
errorPolicy,
94+
fetchPolicy,
95+
fetchResults,
96+
metadata,
97+
notifyOnNetworkStatusChange,
98+
pollInterval,
99+
query,
100+
variables,
101+
}),
101102
[
102103
query,
103104

@@ -112,7 +113,6 @@ export function useQuery<TData = any, TVariables = OperationVariables>(
112113
fetchResults,
113114
]
114115
);
115-
116116
const observableQuery = useMemo(
117117
() =>
118118
getCachedObservableQuery<TData, TVariables>(client, watchQueryOptions),

src/utils.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,16 @@ export function objToKey<T extends Record<string, any>>(obj: T): T | string {
1818
export function isPromiseLike<T>(value: unknown): value is PromiseLike<T> {
1919
return value != null && typeof (value as PromiseLike<T>).then === 'function';
2020
}
21+
22+
export function compact(obj: any) {
23+
return Object.keys(obj).reduce(
24+
(acc, key) => {
25+
if (obj[key] !== undefined) {
26+
acc[key] = obj[key];
27+
}
28+
29+
return acc;
30+
},
31+
{} as any
32+
);
33+
}

0 commit comments

Comments
 (0)