-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathuseLazyQuery.ts
More file actions
655 lines (579 loc) · 22.2 KB
/
Copy pathuseLazyQuery.ts
File metadata and controls
655 lines (579 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import type { TypedDocumentNode } from "@graphql-typed-document-node/core";
import { equal } from "@wry/equality";
import type { DocumentNode } from "graphql";
import * as React from "react";
import type {
ApolloClient,
DataState,
DefaultContext,
ErrorLike,
ErrorPolicy,
GetDataState,
InternalTypes,
MaybeMasked,
ObservableQuery,
OperationVariables,
RefetchOn,
RefetchWritePolicy,
SubscribeToMoreFunction,
UpdateQueryMapFn,
WatchQueryFetchPolicy,
} from "@apollo/client";
import { NetworkStatus } from "@apollo/client";
import type {
DocumentationTypes as UtilityDocumentationTypes,
NoInfer,
OptionWithFallback,
SignatureStyle,
VariablesOption,
} from "@apollo/client/utilities/internal";
import {
maybeDeepFreeze,
variablesUnknownSymbol,
} from "@apollo/client/utilities/internal";
import { invariant } from "@apollo/client/utilities/invariant";
import { useRenderGuard } from "./internal/index.js";
import { useDeepMemo } from "./internal/useDeepMemo.js";
import { useIsomorphicLayoutEffect } from "./internal/useIsomorphicLayoutEffect.js";
import { useApolloClient } from "./useApolloClient.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
export declare namespace useLazyQuery {
import _self = useLazyQuery;
export interface Options<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> {
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */
fetchPolicy?: WatchQueryFetchPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */
nextFetchPolicy?:
| WatchQueryFetchPolicy
| ((
this: ApolloClient.WatchQueryOptions<TData, TVariables>,
currentFetchPolicy: WatchQueryFetchPolicy,
context: InternalTypes.NextFetchPolicyContext<TData, TVariables>
) => WatchQueryFetchPolicy);
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */
refetchWritePolicy?: RefetchWritePolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */
errorPolicy?: ErrorPolicy;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */
pollInterval?: number;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */
notifyOnNetworkStatusChange?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */
returnPartialData?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */
skipPollAttempt?: () => boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */
client?: ApolloClient;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchOn:member} */
refetchOn?: RefetchOn.Option;
}
namespace DocumentationTypes {
namespace useLazyQuery {
export interface Options<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> extends _self.Options<TData, TVariables> {}
}
}
namespace Base {
export interface Result<TData, TVariables extends OperationVariables> {
/** {@inheritDoc @apollo/client!QueryResultDocumentation#startPolling:member} */
startPolling: (pollInterval: number) => void;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#stopPolling:member} */
stopPolling: () => void;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#subscribeToMore:member} */
subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#updateQuery:member} */
updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */
refetch: (
variables?: Partial<TVariables>
) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */
fetchMore: <
TFetchData = TData,
TFetchVars extends OperationVariables = TVariables,
>(
fetchMoreOptions: ObservableQuery.FetchMoreOptions<
TData,
TVariables,
TFetchData,
TFetchVars
>
) => Promise<ApolloClient.QueryResult<MaybeMasked<TFetchData>>>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#client:member} */
client: ApolloClient;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#observable:member} */
observable: ObservableQuery<TData, TVariables>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#previousData:member} */
previousData?: MaybeMasked<TData>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */
error?: ErrorLike;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */
loading: boolean;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */
networkStatus: NetworkStatus;
}
}
export type Result<
TData,
TVariables extends OperationVariables,
TStates extends
DataState<TData>["dataState"] = DataState<TData>["dataState"],
> = Base.Result<TData, TVariables> &
(
| ({
/**
* If `true`, the associated lazy query has been executed.
*
* @docGroup 2. Network info
*/
called: true;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#variables:member} */
variables: TVariables;
} & GetDataState<MaybeMasked<TData>, TStates>)
| {
/**
* If `true`, the associated lazy query has been executed.
*
* @docGroup 2. Network info
*/
called: false;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#variables:member} */
variables: Partial<TVariables>;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */
data: undefined;
/** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */
dataState: "empty";
}
);
namespace DocumentationTypes {
namespace useLazyQuery {
export interface Result<TData, TVariables extends OperationVariables>
extends Base.Result<TData, TVariables>,
UtilityDocumentationTypes.DataState<TData>,
UtilityDocumentationTypes.VariableOptions<TVariables> {
/**
* If `true`, the associated lazy query has been executed.
*
* @docGroup 2. Network info
*/
called: boolean;
}
}
}
export type ExecOptions<
TVariables extends OperationVariables = OperationVariables,
> = {
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */
context?: DefaultContext;
} & VariablesOption<TVariables>;
namespace DocumentationTypes {
namespace useLazyQuery {
export interface ExecOptions<TVariables extends OperationVariables>
extends UtilityDocumentationTypes.VariableOptions<TVariables> {
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */
context?: DefaultContext;
}
}
}
export type ResultTuple<
TData,
TVariables extends OperationVariables,
TStates extends
DataState<TData>["dataState"] = DataState<TData>["dataState"],
> = [
execute: ExecFunction<TData, TVariables>,
result: useLazyQuery.Result<TData, TVariables, TStates>,
];
export type ExecFunction<TData, TVariables extends OperationVariables> = (
...args: {} extends TVariables ?
[options?: useLazyQuery.ExecOptions<TVariables>]
: [options: useLazyQuery.ExecOptions<TVariables>]
) => ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;
namespace DocumentationTypes {
namespace useLazyQuery {
export type { ResultTuple };
}
}
export interface DefaultOptions
extends ApolloClient.DefaultOptions.WatchQuery.Calculated {}
export type ResultForOptions<
TData,
TVariables extends OperationVariables,
TOptions extends Record<string, never> | Options<TData, TVariables>,
> = ResultTuple<
TData,
TVariables,
| "complete"
| "streaming"
| "empty"
| (OptionWithFallback<
TOptions,
DefaultOptions,
"returnPartialData"
> extends false ?
never
: "partial")
>;
namespace DocumentationTypes {
export interface useLazyQuery {
/**
* A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.
*
* > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.
*
* @example
*
* ```jsx
* import { gql } from "@apollo/client";
* import { useLazyQuery } from "@apollo/client/react";
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const [loadGreeting, { called, loading, data }] = useLazyQuery(GET_GREETING, {
* variables: { language: "english" },
* });
* if (called && loading) return <p>Loading ...</p>;
* if (!called) {
* return <button onClick={() => loadGreeting()}>Load greeting</button>;
* }
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
*
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Default options to control how the query is executed.
* @returns A tuple in the form of `[execute, result]`
*/
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<TData, TVariables>
): useLazyQuery.ResultTuple<TData, TVariables>;
}
export interface useLazyQuery_Deprecated {
/**
* @deprecated Avoid manually specifying generics on `useLazyQuery`.
* Instead, rely on TypeScript's type inference along with a correctly typed `TypedDocumentNode` to get accurate types for your query results.
*
* {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)}
*/
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<TData, TVariables>
): useLazyQuery.ResultTuple<TData, TVariables>;
}
}
export namespace Signatures {
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
export interface Classic {
// _INFERENCE_ONLY_DO_NOT_SPECIFY is used to distinguish between inferred
// generics arguments and explicit generic arguments so that we can
// provide a `@deprecated` signature for explicit generic arguments. As
// soon as a user provides a generic arg (e.g. useLazyQuery<TData>(query))`,
// the overload falls through to the overloads without
// _INFERENCE_ONLY_DO_NOT_SPECIFY.
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
}
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
}
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>>
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming"
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
}
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
}
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>>
): useLazyQuery.ResultTuple<
TData,
TVariables,
"empty" | "complete" | "streaming"
>;
}
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
export interface Modern {
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
TOptions extends never,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>
): useLazyQuery.ResultForOptions<
TData,
TVariables,
Record<string, never>
>;
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
TOptions extends useLazyQuery.Options<
NoInfer<TData>,
NoInfer<TVariables>
> & {
variables?: {
[K in Exclude<
keyof TOptions["variables"],
keyof TVariables
>]?: never;
};
},
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: TOptions
): useLazyQuery.ResultForOptions<TData, TVariables, TOptions>;
}
export type Evaluated = SignatureStyle extends "classic" ? Classic : Modern;
}
/** {@inheritDoc @apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:call(1)} */
export interface Signature extends Signatures.Evaluated {}
}
// The following methods, when called will execute the query, regardless of
// whether the useLazyQuery execute function was called before.
const EAGER_METHODS = [
"refetch",
"fetchMore",
"updateQuery",
"startPolling",
"stopPolling",
"subscribeToMore",
] as const;
export const useLazyQuery: useLazyQuery.Signature = function useLazyQuery<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
TStates extends DataState<TData>["dataState"] = DataState<TData>["dataState"],
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options?: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>>
): useLazyQuery.ResultTuple<TData, TVariables, TStates> {
const client = useApolloClient(options?.client);
const previousDataRef = React.useRef<TData>(undefined);
const resultRef = React.useRef<ObservableQuery.Result<TData>>(undefined);
const stableOptions = useDeepMemo(() => options, [options]);
const calledDuringRender = useRenderGuard();
function createObservable() {
return client.watchQuery({
...options,
query,
initialFetchPolicy: options?.fetchPolicy,
fetchPolicy: "standby",
[variablesUnknownSymbol]: true,
} as ApolloClient.WatchQueryOptions<TData, TVariables>);
}
const [currentClient, setCurrentClient] = React.useState(client);
const [observable, setObservable] = React.useState(createObservable);
if (currentClient !== client) {
setCurrentClient(client);
setObservable(createObservable());
}
// TODO: Revisit after we have RxJS in place. We should be able to use
// observable.getCurrentResult() (or equivalent) to get these values which
// will hopefully alleviate the need for us to use refs to track these values.
const updateResult = React.useCallback(
(result: ObservableQuery.Result<TData>, forceUpdate: () => void) => {
const previousData = resultRef.current?.data;
if (previousData && !equal(previousData, result.data)) {
previousDataRef.current = previousData as TData;
}
resultRef.current = result;
forceUpdate();
},
[]
);
const observableResult = useSyncExternalStore(
React.useCallback(
(forceUpdate) => {
const subscription = observable.subscribe((result) => {
if (!equal(resultRef.current, result)) {
updateResult(result, forceUpdate);
}
});
return () => {
subscription.unsubscribe();
};
},
[observable, updateResult]
),
() => resultRef.current || initialResult,
() => initialResult
);
// We use useMemo here to make sure the eager methods have a stable identity.
const eagerMethods = React.useMemo(() => {
const eagerMethods: Record<string, any> = {};
for (const key of EAGER_METHODS) {
eagerMethods[key] = function (...args: any[]) {
invariant(
resultRef.current,
"useLazyQuery: '%s' cannot be called before executing the query.",
key
);
// @ts-expect-error this is just to generic to type
return observable[key](...args);
};
}
return eagerMethods as Pick<
useLazyQuery.Result<TData, TVariables>,
(typeof EAGER_METHODS)[number]
>;
}, [observable]);
React.useEffect(() => {
const updatedOptions: Partial<ObservableQuery.Options<TData, TVariables>> =
{
query,
errorPolicy: stableOptions?.errorPolicy,
refetchOn: stableOptions?.refetchOn,
refetchWritePolicy: stableOptions?.refetchWritePolicy,
returnPartialData: stableOptions?.returnPartialData,
notifyOnNetworkStatusChange: stableOptions?.notifyOnNetworkStatusChange,
pollInterval: stableOptions?.pollInterval,
nextFetchPolicy: options?.nextFetchPolicy,
skipPollAttempt: options?.skipPollAttempt,
};
// Wait to apply the changed fetch policy until after the execute
// function has been called. The execute function will handle setting the
// the fetch policy away from standby for us when called for the first time.
if (
observable.options.fetchPolicy !== "standby" &&
stableOptions?.fetchPolicy
) {
updatedOptions.fetchPolicy = stableOptions.fetchPolicy;
}
observable.applyOptions(updatedOptions);
}, [
query,
observable,
stableOptions,
// Ensure inline functions don't suffer from stale closures by checking for
// these deps separately. @wry/equality doesn't compare function identity
// so `stableOptions` isn't updated when using inline functions.
options?.nextFetchPolicy,
options?.skipPollAttempt,
]);
const execute: useLazyQuery.ExecFunction<TData, TVariables> =
React.useCallback(
(...args) => {
invariant(
!calledDuringRender(),
"useLazyQuery: 'execute' should not be called during render. To start a query during render, use the 'useQuery' hook."
);
const [executeOptions] = args;
let fetchPolicy = observable.options.fetchPolicy;
if (fetchPolicy === "standby") {
fetchPolicy = observable.options.initialFetchPolicy;
}
return observable.reobserve({
fetchPolicy,
// If `variables` is not given, reset back to empty variables by
// ensuring the key exists in options
variables: executeOptions?.variables,
context: executeOptions?.context ?? {},
});
},
[observable, calledDuringRender]
);
const executeRef = React.useRef(execute);
useIsomorphicLayoutEffect(() => {
executeRef.current = execute;
});
const stableExecute = React.useCallback<typeof execute>(
(...args) => executeRef.current(...args),
[]
);
const result = React.useMemo(() => {
const { partial, ...result } = observableResult;
return {
...eagerMethods,
...result,
client,
previousData: previousDataRef.current,
variables: observable.variables,
observable,
called: !!resultRef.current,
};
}, [client, observableResult, eagerMethods, observable]);
return [stableExecute, result as any];
} as any;
const initialResult: ObservableQuery.Result<any> = maybeDeepFreeze({
data: undefined,
dataState: "empty",
loading: false,
networkStatus: NetworkStatus.ready,
partial: true,
});