-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathuseQuery.ts
More file actions
946 lines (850 loc) · 33.7 KB
/
Copy pathuseQuery.ts
File metadata and controls
946 lines (850 loc) · 33.7 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
/**
* Function parameters in this file try to follow a common order for the sake of
* readability and consistency. The order is as follows:
*
* resultData
* observable
* client
* query
* options
* watchQueryOptions
* makeWatchQueryOptions
*/
/** */
import { equal } from "@wry/equality";
import * as React from "react";
import { asapScheduler, observeOn } from "rxjs";
import type {
DataState,
DefaultContext,
DocumentNode,
ErrorLike,
ErrorPolicy,
GetDataState,
InternalTypes,
ObservableQuery,
OperationVariables,
RefetchOn,
RefetchWritePolicy,
SubscribeToMoreFunction,
TypedDocumentNode,
UpdateQueryMapFn,
WatchQueryFetchPolicy,
} from "@apollo/client";
import type { ApolloClient } from "@apollo/client";
import { NetworkStatus } from "@apollo/client";
import type { MaybeMasked } from "@apollo/client/masking";
import type {
DocumentationTypes as UtilityDocumentationTypes,
LazyType,
NoInfer,
OptionWithFallback,
SignatureStyle,
VariablesOption,
} from "@apollo/client/utilities/internal";
import {
maybeDeepFreeze,
mergeOptions,
variablesUnknownSymbol,
} from "@apollo/client/utilities/internal";
import type { SkipToken } from "./constants.js";
import { skipToken } from "./constants.js";
import { useDeepMemo, wrapHook } from "./internal/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
export declare namespace useQuery {
import _self = useQuery;
export namespace Base {
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#initialFetchPolicy:member} */
initialFetchPolicy?: 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#ssr:member} */
ssr?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */
client?: ApolloClient;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */
context?: DefaultContext;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skip:member} */
skip?: boolean;
/** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchOn:member} */
refetchOn?: RefetchOn.Option;
}
}
export type Options<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;
export namespace DocumentationTypes {
namespace useQuery {
export interface Options<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> extends Base.Options<TData, TVariables>,
UtilityDocumentationTypes.VariableOptions<TVariables> {}
}
}
export namespace Base {
export interface Result<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
TReturnVariables extends OperationVariables = TVariables,
> {
/** {@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;
/** {@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#variables:member} */
variables: TReturnVariables;
/** {@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>>>;
}
}
export type Result<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
TStates extends
DataState<TData>["dataState"] = DataState<TData>["dataState"],
TReturnVariables extends OperationVariables = TVariables,
> = Base.Result<TData, TVariables, TReturnVariables> &
GetDataState<MaybeMasked<TData>, TStates>;
export interface DefaultOptions
extends ApolloClient.DefaultOptions.WatchQuery.Calculated {
skip: false;
}
export type ResultForOptions<
TData,
TVariables extends OperationVariables,
TReturnPartialData extends boolean | undefined = undefined,
> = LazyType<
Result<
TData,
TVariables,
| "complete"
| "streaming"
| "empty"
| (OptionWithFallback<
{ returnPartialData: TReturnPartialData },
DefaultOptions,
"returnPartialData"
> extends false ?
never
: "partial")
>
>;
export namespace DocumentationTypes {
namespace useQuery {
export interface Result<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
> extends Base.Result<TData, TVariables>,
UtilityDocumentationTypes.DataState<TData> {}
}
}
export namespace DocumentationTypes {
export interface useQuery {
/**
* A hook for executing queries in an Apollo application.
*
* To run a query within a React component, call `useQuery` and pass it a GraphQL query document.
*
* When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, `dataState`, and `data` properties you can use to render your UI.
*
* > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.
*
* @example
*
* ```jsx
* import { gql } from "@apollo/client";
* import { useQuery } from "@apollo/client/react";
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const { loading, error, data } = useQuery(GET_GREETING, {
* variables: { language: "english" },
* });
* if (loading) return <p>Loading ...</p>;
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
*
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Options to control how the query is executed.
* @returns Query result object
*/
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<TData, TVariables>
): useQuery.Result<TData, TVariables>;
}
export interface useQuery_Deprecated {
/**
* @deprecated Avoid manually specifying generics on `useQuery`.
* 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!useQuery.DocumentationTypes.useQuery:call(1)}
*/
<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<TData, TVariables>
): useQuery.Result<TData, TVariables>;
}
}
export namespace Signatures {
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery: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. useQuery<TData>(query))`,
// the overload falls through to the overloads without
// _INFERENCE_ONLY_DO_NOT_SPECIFY.
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
}
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: SkipToken
): useQuery.Result<TData, TVariables, "empty", Record<string, never>>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options:
| SkipToken
| (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
})
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial",
Partial<TVariables>
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
}
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options:
| SkipToken
| (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
})
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial",
Partial<TVariables>
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: {} extends TVariables ?
[options?: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]
: [options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]
): useQuery.Result<TData, TVariables, "empty" | "complete" | "streaming">;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
_INFERENCE_ONLY_DO_NOT_SPECIFY extends "inferred",
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: {} extends TVariables ?
[
options?:
| SkipToken
| useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
]
: [
options:
| SkipToken
| useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
]
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming",
Partial<TVariables>
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
}
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: SkipToken
): useQuery.Result<TData, TVariables, "empty", Record<string, never>>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options:
| SkipToken
| (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
})
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial",
Partial<TVariables>
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
}
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial"
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options:
| SkipToken
| (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: boolean;
})
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming" | "partial",
Partial<TVariables>
>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: {} extends TVariables ?
[options?: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]
: [options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]
): useQuery.Result<TData, TVariables, "empty" | "complete" | "streaming">;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery_Deprecated:call(1)} */
<TData, TVariables extends OperationVariables = OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: {} extends TVariables ?
[
options?:
| SkipToken
| useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
]
: [
options:
| SkipToken
| useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
]
): useQuery.Result<
TData,
TVariables,
"empty" | "complete" | "streaming",
Partial<TVariables>
>;
ssrDisabledResult: ObservableQuery.Result<any>;
}
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
export interface Modern {
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
Options extends never,
>(
query: {} extends TVariables ?
DocumentNode | TypedDocumentNode<TData, TVariables>
: // this overload should only be accessible if all `TVariables` are optional
never
): useQuery.ResultForOptions<TData, TVariables>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
TProvidedVariables extends TVariables & {
[K in Exclude<keyof TProvidedVariables, keyof TVariables>]?: never;
} = TVariables,
TReturnPartialData extends boolean | undefined = undefined,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: // we generally do not allow for a `TVariables` of `never`
// TODO: check if we need a similar check in other hooks
[TVariables] extends [never] ? [options: never]
: // variables optional
{} extends TVariables ?
[
options?: useQuery.Base.Options<TData, NoInfer<TVariables>> & {
variables?: TProvidedVariables;
returnPartialData?: TReturnPartialData;
},
]
: // variables required
[
options: useQuery.Base.Options<TData, NoInfer<TVariables>> & {
variables: TProvidedVariables;
returnPartialData?: TReturnPartialData;
},
]
): useQuery.ResultForOptions<TData, TVariables, TReturnPartialData>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
TOptions extends SkipToken,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: SkipToken
): useQuery.Result<TData, TVariables, "empty", Record<string, never>>;
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
<
TData,
TVariables extends OperationVariables,
// this overload should never be manually defined, it should always be inferred
TProvidedVariables extends TVariables & {
[K in Exclude<keyof TProvidedVariables, keyof TVariables>]?: never;
} = TVariables,
TReturnPartialData extends boolean | undefined = undefined,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: // we generally do not allow for a `TVariables` of `never`
// TODO: check if we need a similar check in other hooks
[TVariables] extends [never] ? [options: never]
: // variables optional
{} extends TVariables ?
[
options?:
| (useQuery.Base.Options<TData, NoInfer<TVariables>> & {
variables?: TProvidedVariables;
returnPartialData?: TReturnPartialData;
})
| SkipToken,
]
: // variables required
[
options:
| (useQuery.Base.Options<TData, NoInfer<TVariables>> & {
variables: TProvidedVariables;
returnPartialData?: TReturnPartialData;
})
| SkipToken,
]
): useQuery.ResultForOptions<TData, TVariables, TReturnPartialData>;
ssrDisabledResult: ObservableQuery.Result<any>;
}
export type Evaluated = SignatureStyle extends "classic" ? Classic : Modern;
}
/** {@inheritDoc @apollo/client/react!useQuery.DocumentationTypes.useQuery:call(1)} */
export interface Signature extends Signatures.Evaluated {}
}
const lastWatchOptions = Symbol();
interface ObsQueryWithMeta<TData, TVariables extends OperationVariables>
extends ObservableQuery<TData, TVariables> {
[lastWatchOptions]?: Readonly<
ApolloClient.WatchQueryOptions<TData, TVariables>
>;
}
interface InternalResult<TData> {
// These members are populated by getCurrentResult and setResult, and it's
// okay/normal for them to be initially undefined.
current: ObservableQuery.Result<TData>;
previousData?: undefined | MaybeMasked<TData>;
// Track current variables separately in case a call to e.g. `refetch(newVars)`
// causes an emit that is deeply equal to the current result. This lets us
// compare if we should force rerender due to changed variables
variables: OperationVariables;
}
interface InternalState<TData, TVariables extends OperationVariables> {
client: ReturnType<typeof useApolloClient>;
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
observable: ObsQueryWithMeta<TData, TVariables>;
resultData: InternalResult<TData>;
}
export const useQuery: useQuery.Signature = function useQuery<
TData = unknown,
TVariables extends OperationVariables = OperationVariables,
>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
...[options]: {} extends TVariables ?
[
options?:
| SkipToken
| useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
]
: [options: SkipToken | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]
): useQuery.Result<TData, TVariables> {
"use no memo";
return wrapHook(
"useQuery",
useQuery_,
useApolloClient(typeof options === "object" ? options.client : undefined)
)(query, options);
} as any;
function useQuery_<TData, TVariables extends OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options:
| SkipToken
| useQuery.Options<
NoInfer<TData>,
NoInfer<TVariables>
> = {} as useQuery.Options<TData, TVariables>
): useQuery.Result<TData, TVariables> {
const client = useApolloClient(
typeof options === "object" ? options.client : undefined
);
const { ssr } = typeof options === "object" ? options : {};
const watchQueryOptions = useOptions(
query,
options,
client.defaultOptions.watchQuery
);
function createState(
previous?: InternalState<TData, TVariables>
): InternalState<TData, TVariables> {
const observable = client.watchQuery(watchQueryOptions);
return {
client,
query,
observable,
resultData: {
current: observable.getCurrentResult(),
// Reuse previousData from previous InternalState (if any) to provide
// continuity of previousData even if/when the query or client changes.
previousData: previous?.resultData.current.data as TData,
variables: observable.variables,
},
};
}
let [state, setState] = React.useState(createState);
if (client !== state.client || query !== state.query) {
// If the client or query have changed, we need to create a new InternalState.
// This will trigger a re-render with the new state, but it will also continue
// to run the current render function to completion.
// Since we sometimes trigger some side-effects in the render function, we
// re-assign `state` to the new state to ensure that those side-effects are
// triggered with the new state.
setState((state = createState(state)));
}
const { observable, resultData } = state;
useInitialFetchPolicyIfNecessary<TData, TVariables>(
watchQueryOptions,
observable
);
useResubscribeIfNecessary<TData, TVariables>(
resultData, // might get mutated during render
observable, // might get mutated during render
watchQueryOptions
);
const result = useResult<TData, TVariables>(observable, resultData, ssr);
const obsQueryFields = React.useMemo(
() => ({
refetch: observable.refetch.bind(observable),
fetchMore: observable.fetchMore.bind(observable),
updateQuery: observable.updateQuery.bind(observable),
startPolling: observable.startPolling.bind(observable),
stopPolling: observable.stopPolling.bind(observable),
subscribeToMore: observable.subscribeToMore.bind(observable),
}),
[observable]
);
const previousData = resultData.previousData;
return React.useMemo(() => {
const { partial, ...rest } = result;
return {
...rest,
client,
observable,
variables: observable.variables,
previousData,
...obsQueryFields,
};
}, [result, client, observable, previousData, obsQueryFields]);
}
const fromSkipToken = Symbol();
function useOptions<TData, TVariables extends OperationVariables>(
query: DocumentNode | TypedDocumentNode<TData, TVariables>,
options: SkipToken | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,
defaultOptions: Partial<ApolloClient.WatchQueryOptions<any, any>> | undefined
): ApolloClient.WatchQueryOptions<TData, TVariables> {
return useDeepMemo<ApolloClient.WatchQueryOptions<TData, TVariables>>(() => {
if (options === skipToken) {
const opts: ApolloClient.WatchQueryOptions<TData, TVariables> = {
...mergeOptions(defaultOptions as any, {
query,
fetchPolicy: "standby",
}),
[variablesUnknownSymbol]: true,
};
(opts as any)[fromSkipToken] = true;
return opts;
}
const watchQueryOptions: ApolloClient.WatchQueryOptions<TData, TVariables> =
mergeOptions(defaultOptions as any, { ...options, query });
if (options.skip) {
watchQueryOptions.initialFetchPolicy =
options.initialFetchPolicy || options.fetchPolicy;
watchQueryOptions.fetchPolicy = "standby";
}
return watchQueryOptions;
}, [query, options, defaultOptions]);
}
function useInitialFetchPolicyIfNecessary<
TData,
TVariables extends OperationVariables,
>(
watchQueryOptions: ApolloClient.WatchQueryOptions<TData, TVariables>,
observable: ObsQueryWithMeta<TData, TVariables>
) {
"use no memo";
if (!watchQueryOptions.fetchPolicy) {
watchQueryOptions.fetchPolicy = observable.options.initialFetchPolicy;
}
}
function useResult<TData, TVariables extends OperationVariables>(
observable: ObsQueryWithMeta<TData, TVariables>,
resultData: InternalResult<TData>,
ssr: boolean | undefined
) {
"use no memo";
const fetchPolicy = observable.options.fetchPolicy;
return useSyncExternalStore(
React.useCallback(
(handleStoreChange) => {
const subscription = observable
// We use the asapScheduler here to prevent issues with trying to
// update in the middle of a render. `reobserve` is kicked off in the
// middle of a render and because RxJS emits values synchronously,
// its possible for this `handleStoreChange` to be called in that same
// render. This allows the render to complete before trying to emit a
// new value.
.pipe(observeOn(asapScheduler))
.subscribe((result) => {
const previous = resultData.current;
if (
// Avoid rerendering if the result is the same
equal(previous, result) &&
// Force rerender if the value was emitted because variables
// changed, such as when calling `refetch(newVars)` which returns
// the same data when `notifyOnNetworkStatusChange` is `false`.
equal(resultData.variables, observable.variables)
) {
return;
}
resultData.variables = observable.variables;
if (previous.data && !equal(previous.data, result.data)) {
resultData.previousData = previous.data as TData;
}
resultData.current = result;
handleStoreChange();
});
// Do the "unsubscribe" with a short delay.
// This way, an existing subscription can be reused without an additional
// request if "unsubscribe" and "resubscribe" to the same ObservableQuery
// happen in very fast succession.
return () => {
setTimeout(() => subscription.unsubscribe());
};
},
[observable, resultData]
),
() => resultData.current,
() =>
(
(fetchPolicy !== "standby" && ssr === false) ||
fetchPolicy === "no-cache"
) ?
useQuery.ssrDisabledResult
: resultData.current
);
}
// this hook is not compatible with any rules of React, and there's no good way to rewrite it.
// it should stay a separate hook that will not be optimized by the compiler
function useResubscribeIfNecessary<
TData,
TVariables extends OperationVariables,
>(
/** this hook will mutate properties on `resultData` */
resultData: InternalResult<TData>,
/** this hook will mutate properties on `observable` */
observable: ObsQueryWithMeta<TData, TVariables>,
watchQueryOptions: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>
) {
"use no memo";
if (
observable[lastWatchOptions] &&
!equal(observable[lastWatchOptions], watchQueryOptions)
) {
// If skipToken was used to generate options, we won't know the correct
// initialFetchPolicy until the hook is rerendered with real options, so we
// set it the next time we get real options
if (
(observable[lastWatchOptions] as any)[fromSkipToken] &&
!watchQueryOptions.initialFetchPolicy
) {
(watchQueryOptions.initialFetchPolicy as any) =
watchQueryOptions.fetchPolicy;
}
// Though it might be tempting to postpone this reobserve call to the
// useEffect block, we need getCurrentResult to return an appropriate
// loading:true result synchronously (later within the same call to
// useQuery). Since we already have this.observable here (not true for
// the very first call to useQuery), we are not initiating any new
// subscriptions, though it does feel less than ideal that reobserve
// (potentially) kicks off a network request (for example, when the
// variables have changed), which is technically a side-effect.
if (shouldReobserve(observable[lastWatchOptions], watchQueryOptions)) {
observable.reobserve(watchQueryOptions);
} else {
observable.applyOptions(watchQueryOptions);
}
// Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,
// but save the current data as this.previousData, just like setResult
// usually does.
const result = observable.getCurrentResult();
if (!equal(result.data, resultData.current.data)) {
resultData.previousData = (resultData.current.data ||
(resultData.previousData as TData)) as TData;
}
resultData.current = result;
resultData.variables = observable.variables;
}
observable[lastWatchOptions] = watchQueryOptions;
}
function shouldReobserve<TData, TVariables extends OperationVariables>(
previousOptions: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>,
options: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>
) {
return (
previousOptions.query !== options.query ||
!equal(previousOptions.variables, options.variables) ||
(previousOptions.fetchPolicy !== options.fetchPolicy &&
(options.fetchPolicy === "standby" ||
previousOptions.fetchPolicy === "standby"))
);
}
useQuery.ssrDisabledResult = maybeDeepFreeze({
loading: true,
data: void 0 as any,
dataState: "empty",
error: void 0,
networkStatus: NetworkStatus.loading,
partial: true,
}) satisfies ObservableQuery.Result<any> as ObservableQuery.Result<any>;