@jsb188/graphql 1.0.2 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hooks/index.ts ADDED
@@ -0,0 +1,791 @@
1
+ import { getENVVariable } from '@jsb188/app';
2
+ import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
3
+ import { normalizeServerError } from '@jsb188/app/utils/api';
4
+ import { delay } from '@jsb188/app/utils/logic';
5
+ import { isServerErrorGQL } from '@jsb188/graphql/utils';
6
+ import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
7
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
+ import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
9
+ import { QUERY_EXPIRE_TIMES } from '../cache/config';
10
+ import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
11
+ import { graphqlRequest } from '../client/request';
12
+
13
+
14
+ /**
15
+ * Types; mutation
16
+ */
17
+
18
+ export type GraphQLMutationFn = (graphqlOptions?: GraphQLRequestOptions, triedCount?: number) => Promise<any>;
19
+
20
+ type GraphQLMutationOptions = Partial<{
21
+ checkMountedBeforeCallback: boolean;
22
+ authToken: string;
23
+ retryCount: number;
24
+ variables: Record<string, any> | null;
25
+ cacheMap: any;
26
+ openModalPopUp: AnyModalPopUpFn | null;
27
+ initialError: any;
28
+ onCompleted: OnCompletedGQLFn;
29
+ onError: OnErrorGQLFn;
30
+ }>;
31
+
32
+ type GraphQLMutationResult = {
33
+ data: any | null;
34
+ variables: Record<string, any> | null;
35
+ saving: boolean;
36
+ error: ServerErrorObj | null;
37
+ };
38
+
39
+ type GraphQLMutation = [
40
+ GraphQLMutationFn,
41
+ GraphQLMutationResult,
42
+ GraphQLHandlers,
43
+ UpdateObserversFn,
44
+ React.MutableRefObject<boolean>
45
+ ];
46
+
47
+ /**
48
+ * Types; query
49
+ */
50
+
51
+ type GraphQLRequestOptions = {
52
+ variables?: Record<string, any> | null;
53
+ };
54
+
55
+ type GraphQLQueryResult = {
56
+ data: any | null;
57
+ variables?: Record<string, any> | null;
58
+ loading: boolean;
59
+ error: ServerErrorObj | null;
60
+ refetch: () => void;
61
+ fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
62
+ queryName: string;
63
+ queryKey: string;
64
+ variablesKey: string;
65
+ updatedCount: number;
66
+ updateObservers: UpdateObserversFn;
67
+ connectedToServer: boolean;
68
+ screenIsFocused: boolean;
69
+ };
70
+
71
+ /**
72
+ * Global variables
73
+ */
74
+
75
+ const QRY_TRACKER = new Map();
76
+
77
+ /**
78
+ * Global; unset query tracker
79
+ */
80
+
81
+ function unsetQueryTracker(queryName: string, unique: string | null) {
82
+ const currentHookId = QRY_TRACKER.get(queryName);
83
+ if (currentHookId === unique) {
84
+ QRY_TRACKER.delete(queryName);
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Helper; get retry delay
90
+ */
91
+
92
+ function getRetryDelay(triedCount: number): number {
93
+ return 1500 * Math.pow(2, triedCount);
94
+ }
95
+
96
+ /**
97
+ * Update data observer
98
+ */
99
+
100
+ export function useUpdateObservers(): UpdateObserversFn {
101
+ const setQueryObserver = useSetQueryObserver();
102
+ const setFragmentObserver = useSetFragmentObserver();
103
+
104
+ return (args: UpdateDataObserverArgs) => {
105
+ if (args.queryId) {
106
+ setQueryObserver((prev: any) => ({
107
+ count: (prev.name === args.queryId ? prev.count : 0) + 1,
108
+ name: args.queryId as string,
109
+ forceRefetch: !!args.forceRefetch,
110
+ }));
111
+ }
112
+
113
+ if (args.fragmentIds?.length) {
114
+ setFragmentObserver((prev: any) => ({
115
+ count: (prev.count || 0) + 1,
116
+ list: args.fragmentIds as string[],
117
+ }));
118
+ }
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Hook for query changes
124
+ */
125
+
126
+ export function useWatchQuery(
127
+ query: any,
128
+ variablesKey: string,
129
+ ): [number, boolean] { // [updatedCount, forceRefetch]
130
+
131
+ const queryObserver = useQueryObserverValue();
132
+
133
+ return useMemo(() => {
134
+ if (queryObserver.name) {
135
+ const matchedQry = query.definitions
136
+ .filter((d: any) => d.kind === 'OperationDefinition')
137
+ .find((d: any) => queryObserver.name.startsWith('#' + d.name.value));
138
+
139
+ if (!matchedQry) {
140
+ return [0, false];
141
+ }
142
+
143
+ // console.log('matchedQry:', matchedQry);
144
+ // console.log('queryObserver:', queryObserver);
145
+
146
+ const queryName = matchedQry.name.value;
147
+ const queryId = `#${queryName}:${variablesKey}`;
148
+
149
+ return [
150
+ queryObserver.name === queryId ? queryObserver.count : 0,
151
+ !!queryObserver.forceRefetch,
152
+ ];
153
+ }
154
+
155
+ return [0, false];
156
+ }, [queryObserver]);
157
+ }
158
+
159
+ /**
160
+ * Hook for reactive fragment data
161
+ */
162
+
163
+ export function useReactiveFragment(
164
+ data_: any,
165
+ observe: Array<string | string[]>,
166
+ qryObsCount?: number,
167
+ otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
168
+ ignoreIDWarning?: boolean,
169
+ // doTest?: boolean
170
+ ) {
171
+
172
+ const data = data_ || {};
173
+ const fragmentObserver = useFragmentObserverValue();
174
+ const frgObsCount = fragmentObserver.count;
175
+ const [changedData, setChangedData] = useState<any>({
176
+ fragmentUpdatedCount: frgObsCount,
177
+ queryUpdatedCount: qryObsCount,
178
+ data
179
+ });
180
+
181
+ if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
182
+ // this is fine because it will only run in development and never truly be conditional
183
+ // eslint-disable-next-line react-hooks/rules-of-hooks
184
+ useEffect(() => {
185
+ if (
186
+ // getENVVariable('NODE_ENV') === 'development' &&
187
+ data.id && changedData.data?.id &&
188
+ data.id !== changedData.data?.id
189
+ ) {
190
+ console.warn(`WARNING: useReactiveFragment() data.id changed from ${data.id} to ${changedData.data?.id}`);
191
+ console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
192
+ }
193
+ }, [changedData.data?.id]);
194
+ }
195
+
196
+ useEffect(() => {
197
+ // NOTE: I tried this with effect()
198
+ // But that caused the render to happen 3 times more, I don't know why.
199
+ // I only solved it by using useEffect()
200
+ const idsChanged = (
201
+ changedData.data.id !== data.id ||
202
+ (
203
+ // This is absolutely needed for the chat clientId system to work properly;
204
+ // Otherwise messages will be stuck in "not sent" state.
205
+ changedData.data.clientId &&
206
+ changedData.data.clientId !== data.clientId
207
+ )
208
+ );
209
+
210
+ const forceReactive = otherCheck && otherCheck(changedData.data, fragmentObserver.list);
211
+
212
+ if (
213
+ idsChanged ||
214
+ forceReactive || (
215
+ (changedData.data || data) &&
216
+ (
217
+ frgObsCount !== changedData.fragmentUpdatedCount ||
218
+ qryObsCount !== changedData.queryUpdatedCount
219
+ )
220
+ )
221
+ ) {
222
+
223
+ // if (doTest) {
224
+ // console.log('DO TEST:');
225
+ // console.log(observe);
226
+ // console.log(fragmentObserver);
227
+ // }
228
+
229
+ let newData;
230
+ for (const key of observe) {
231
+ const isMapped = Array.isArray(key);
232
+ if (
233
+ key && (
234
+ idsChanged ||
235
+ forceReactive ||
236
+ (isMapped && fragmentObserver.list.includes(key[0])) ||
237
+ (!isMapped && fragmentObserver.list.includes(key))
238
+ )
239
+ ) {
240
+ if (!newData) {
241
+ if (idsChanged) {
242
+ newData = data;
243
+ } else if (data) {
244
+ newData = {
245
+ ...data,
246
+ ...changedData.data,
247
+ };
248
+ } else {
249
+ newData = changedData.data;
250
+ }
251
+ }
252
+
253
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
254
+ if (fragmentData) {
255
+ if (isMapped) {
256
+ newData = {
257
+ ...newData,
258
+ [key[1]]: fragmentData,
259
+ };
260
+ } else {
261
+ newData = {
262
+ ...newData,
263
+ ...fragmentData,
264
+ };
265
+ }
266
+ }
267
+ }
268
+ }
269
+
270
+ if (newData) {
271
+ setChangedData({
272
+ data: newData,
273
+ fragmentUpdatedCount: frgObsCount,
274
+ queryUpdatedCount: qryObsCount,
275
+ });
276
+ }
277
+ }
278
+ }, [data.id, qryObsCount, frgObsCount]);
279
+
280
+ // This is not needed now, I think
281
+ // useEffect(() => {
282
+ // if (updateQueryCount && queryKey) {
283
+ // const updatedQueryData = loadQuery(queryKey);
284
+ // setChangedData({
285
+ // ...changedData,
286
+ // data: {
287
+ // ...changedData.data,
288
+ // ...updatedQueryData,
289
+ // },
290
+ // });
291
+ // }
292
+ // }, [updateQueryCount]);
293
+
294
+ return changedData.data;
295
+ }
296
+
297
+ /**
298
+ * Observe query changes; but for Arrays
299
+ */
300
+
301
+ export function useReactiveFragmentMap(
302
+ data: any[] | null,
303
+ fragmentName_: string,
304
+ ) {
305
+ const fragmentName = `$${fragmentName_}`;
306
+ const observe = data?.map((d) => fragmentName + ':' + d.id);
307
+ const fragmentObserver = useFragmentObserverValue();
308
+
309
+ const [changedData, setChangedData] = useState({
310
+ count: fragmentObserver.count,
311
+ lastObserve: observe,
312
+ data
313
+ });
314
+
315
+ useEffect(() => {
316
+ // NOTE: I tried this with effect()
317
+ // But that caused the render to happen 3 times more, I don't know why.
318
+ // I only solved it by using useEffect()
319
+
320
+ const dataToUpdate = changedData.data || data;
321
+ if (
322
+ dataToUpdate &&
323
+ observe &&
324
+ fragmentObserver.count !== changedData.count
325
+ ) {
326
+ let newData;
327
+ for (let i = 0; i < observe.length; i++) {
328
+ const key = observe[i];
329
+
330
+ if (fragmentObserver.list.includes(key)) {
331
+ if (!newData) {
332
+ newData = dataToUpdate;
333
+ }
334
+
335
+ if (newData[i]) {
336
+ const fragmentData = loadFragment(key);
337
+ if (fragmentData) {
338
+ newData[i] = {
339
+ ...newData[i],
340
+ ...fragmentData,
341
+ };
342
+ }
343
+ }
344
+ }
345
+ }
346
+
347
+ if (newData) {
348
+ setChangedData({
349
+ ...changedData,
350
+ count: fragmentObserver.count,
351
+ data: newData.slice(0)
352
+ });
353
+ }
354
+ }
355
+ }, [fragmentObserver.list]);
356
+
357
+ const observeStr = observe?.join(',');
358
+ useEffect(() => {
359
+ if (changedData.lastObserve?.join(',') !== observeStr) {
360
+ setChangedData({
361
+ ...changedData,
362
+ data,
363
+ lastObserve: observe,
364
+ });
365
+ }
366
+ }, [observeStr]);
367
+
368
+ return changedData.data;
369
+ }
370
+
371
+ /**
372
+ * Use mutation
373
+ */
374
+
375
+ export function useMutation(
376
+ mutation: any,
377
+ options?: GraphQLMutationOptions,
378
+ ): GraphQLMutation {
379
+
380
+ const { onCompleted, onError, openModalPopUp, initialError, checkMountedBeforeCallback } = options || {};
381
+ const updateObservers = useUpdateObservers();
382
+
383
+ // No need to abort mutations
384
+ // But bring it back if you want ability to "cancel"
385
+ // const controller = useRef();
386
+
387
+ const mounted = useRef(true);
388
+ const [mtnValues, setMtnValues] = useState({
389
+ variables: null as Record<string, any> | null,
390
+ saving: false,
391
+ data: null,
392
+ error: initialError || null as ServerErrorObj | null
393
+ });
394
+
395
+ // Mounted hook
396
+
397
+ useEffect(() => {
398
+ return () => {
399
+ mounted.current = false;
400
+ };
401
+ }, []);
402
+
403
+ // Mutate function for the client
404
+
405
+ const doMutate = async (
406
+ graphqlOptions?: GraphQLRequestOptions,
407
+ triedCount: number = 0,
408
+ ) => {
409
+ // No need to abort mutations
410
+ // if (controller.current) {
411
+ // controller.current.abort();
412
+ // }
413
+
414
+ // No need to abort mutations
415
+ // controller.current = new AbortController();
416
+
417
+ setMtnValues({
418
+ ...mtnValues,
419
+ variables: graphqlOptions?.variables || null,
420
+ saving: true,
421
+ });
422
+
423
+ const retryCount = options?.retryCount || 0;
424
+ const retryDelay = getRetryDelay(triedCount);
425
+
426
+ const apiResult = await graphqlRequest(
427
+ mutation,
428
+ graphqlOptions?.variables,
429
+ {
430
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
431
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
432
+ if (mounted.current) {
433
+ setMtnValues({
434
+ ...mtnValues,
435
+ saving: false,
436
+ data: data.data || null,
437
+ error,
438
+ });
439
+ }
440
+
441
+ if (data.data) {
442
+ if (onCompleted && (mounted.current || !checkMountedBeforeCallback)) {
443
+ // Do separate {mounted.current} check from outside
444
+ onCompleted(data.data, error, graphqlOptions?.variables);
445
+ }
446
+ }
447
+ },
448
+ onError: (error: ServerErrorObj | null) => {
449
+ if (mounted.current) {
450
+ setMtnValues({
451
+ ...mtnValues,
452
+ saving: retryCount > triedCount,
453
+ error,
454
+ });
455
+ }
456
+
457
+ if (onError && retryCount <= triedCount && (mounted.current || !checkMountedBeforeCallback)) {
458
+ onError(error, graphqlOptions?.variables);
459
+ }
460
+ },
461
+ },
462
+ null, // abort controller is not needed for mutations
463
+ updateObservers
464
+ );
465
+
466
+ if (apiResult.aborted) {
467
+ return apiResult;
468
+ }
469
+
470
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
471
+ if (retryCount > triedCount) {
472
+ await delay(retryDelay);
473
+ if (getENVVariable('NODE_ENV') === 'development') {
474
+ console.log(`retrying mutation... ${triedCount + 1} / ${retryCount}`);
475
+ }
476
+
477
+ return doMutate(graphqlOptions, triedCount + 1);
478
+ } else if (getENVVariable('NODE_ENV') === 'development') {
479
+ console.log(
480
+ `mutation failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
481
+ );
482
+ }
483
+ }
484
+
485
+ return apiResult;
486
+ };
487
+
488
+ const mtnHandlers: GraphQLHandlers = {
489
+ resetErrors: function () {
490
+ setMtnValues({
491
+ ...mtnValues,
492
+ error: null,
493
+ });
494
+ },
495
+ setError: function (errorObj: SimpleErrorType) {
496
+ setMtnValues({
497
+ ...mtnValues,
498
+ error: {
499
+ ...errorObj,
500
+ statusCode: 200,
501
+ errorCode: 'custom_error',
502
+ },
503
+ });
504
+ },
505
+ refetch: function () {
506
+ const lastVariables = mtnValues.variables;
507
+ return doMutate(lastVariables ? { variables: lastVariables } : undefined);
508
+ },
509
+ };
510
+
511
+ // useEffect(() => {
512
+ // return () => {
513
+ // if (controller.current) {
514
+ // controller.current.abort();
515
+ // }
516
+ // };
517
+ // }, []);
518
+
519
+ return [doMutate, mtnValues, mtnHandlers, updateObservers, mounted];
520
+ }
521
+
522
+ /**
523
+ * Use query
524
+ */
525
+
526
+ export function useQuery(
527
+ query: any,
528
+ options?: GraphQLQueryOptions,
529
+ ): GraphQLQueryResult {
530
+ const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap } = options || {};
531
+ const variablesKey = makeVariablesKey(variables);
532
+ const connectedToServer = useConnectedToServerValue();
533
+ const screenIsFocused = useScreenIsFocusedValue();
534
+ const updateObservers = useUpdateObservers();
535
+ const [updatedCount, forceRefetch] = useWatchQuery(query, variablesKey);
536
+
537
+ // useQuery() assumes query is a single graphql query (and not a multi/chain)
538
+ // Multiple queries can be chained using this hook,
539
+ // but only the first query is used for tracking reactivity.
540
+ const queryName = query.definitions?.[0]?.name?.value;
541
+ const queryKey = `#${queryName}:${variablesKey}`;
542
+
543
+ const tracker = useRef({
544
+ unique: null as string | null,
545
+ abortCtrl: null as AbortController | null,
546
+ reconnectedAt: null as number | null,
547
+ init: false
548
+ });
549
+
550
+ // check if p.updatedCount is needed
551
+
552
+ const [qryValues, setQryValues] = useState({
553
+ data: null as any,
554
+ variables,
555
+ loading: false,
556
+ error: null as ServerErrorObj | null,
557
+ lastUpdatedCount: 0
558
+ });
559
+
560
+ // Query function for the client
561
+ // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
562
+
563
+ const doQuery = async (queryVariables?: any, triedCount: number = 0) => {
564
+
565
+ const currentHookId = QRY_TRACKER.get(queryKey);
566
+
567
+ if (!currentHookId) {
568
+ QRY_TRACKER.set(queryKey, tracker.current.unique);
569
+ } else if (currentHookId) {
570
+ // This query is being fetched already, so do nothing
571
+ // This can happen in 2 ways;
572
+ // 1. This hook is used to doQuery() while doQuery() is alerady in progress (loading)
573
+ // 2. useWatchQuery() caused 2 hooks with same query to be called at once
574
+ return;
575
+ }
576
+
577
+ if (tracker.current.abortCtrl && qryValues.loading) {
578
+ // doLog(query, 'Query component [$0] is being aborted before being refetched.');
579
+ // console.log('ABORT:', queryKey, tracker.current.unique);
580
+ tracker.current.abortCtrl.abort({
581
+ name: 'AbortError',
582
+ message: `Hook for ${queryKey} has aborted because the [query refetched before the previous one ended].`
583
+ });
584
+ }
585
+
586
+ tracker.current.abortCtrl = new AbortController();
587
+
588
+ setQryValues({
589
+ ...qryValues,
590
+ loading: true,
591
+ });
592
+
593
+ const retryCount = options?.retryCount || 0;
594
+ const retryDelay = getRetryDelay(triedCount);
595
+ const qryVariables = queryVariables || variables;
596
+ // const qryName = query.definitions?.[0]?.name?.value;
597
+
598
+ // doLog(query, 'Query component [$0] is being refetched.');
599
+
600
+ const apiResult = await graphqlRequest(
601
+ query,
602
+ qryVariables,
603
+ {
604
+ openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
605
+ cacheMap,
606
+ onCompleted: (data: any | null, error: ServerErrorObj | null) => {
607
+ if (data.data) {
608
+ setQryValues({
609
+ ...qryValues,
610
+ variables: qryVariables,
611
+ data: data.data,
612
+ loading: false,
613
+ error,
614
+ });
615
+
616
+ if (onCompleted) {
617
+ onCompleted(data.data, error, qryVariables);
618
+ }
619
+
620
+ removeStaleCache();
621
+ tracker.current.reconnectedAt = Date.now();
622
+ }
623
+
624
+ unsetQueryTracker(queryKey, tracker.current.unique);
625
+ },
626
+ onError: (error: ServerErrorObj | null) => {
627
+ setQryValues({
628
+ ...qryValues,
629
+ variables: qryVariables,
630
+ loading: retryCount > triedCount,
631
+ error,
632
+ });
633
+
634
+ if (onError && retryCount <= triedCount) {
635
+ onError(error, qryVariables);
636
+ }
637
+
638
+ unsetQueryTracker(queryKey, tracker.current.unique);
639
+ },
640
+ },
641
+ tracker.current.abortCtrl.signal,
642
+ updateObservers
643
+ );
644
+
645
+ if (apiResult.aborted) {
646
+ return apiResult;
647
+ }
648
+
649
+ if (!apiResult.data && isServerErrorGQL(apiResult)) {
650
+ if (retryCount > triedCount) {
651
+ await delay(retryDelay);
652
+ if (getENVVariable('NODE_ENV') === 'development') {
653
+ console.log(`retrying query... ${triedCount + 1} / ${retryCount}`);
654
+ }
655
+
656
+ return doQuery(queryVariables, triedCount + 1);
657
+ } else if (getENVVariable('NODE_ENV') === 'development') {
658
+ console.log(
659
+ `query failed; exhausted all retry attempts... ${triedCount} / ${retryCount}`,
660
+ );
661
+ }
662
+ }
663
+
664
+ return apiResult;
665
+ };
666
+
667
+ // Mount & unmount
668
+
669
+ useEffect(() => {
670
+ if (!tracker.current.unique) {
671
+ tracker.current.unique = Date.now().toString(36) + Math.random().toString(36).substring(2);
672
+ }
673
+
674
+ return () => {
675
+ unsetQueryTracker(queryKey, tracker.current.unique);
676
+
677
+ if (tracker.current.abortCtrl) {
678
+ // console.log('UMOUNTED:', queryKey, tracker.current.unique);
679
+ tracker.current.abortCtrl.abort({
680
+ name: 'AbortError',
681
+ message: `Hook for ${queryKey} has aborted because [the component unmounted].`
682
+ });
683
+ }
684
+ };
685
+ }, [queryKey]);
686
+
687
+ // Refetch when variables, skip status or query observer changes
688
+
689
+ useEffect(() => {
690
+ if (
691
+ !skip && (
692
+ updatedCount !== qryValues.lastUpdatedCount ||
693
+ variablesKey !== makeVariablesKey(qryValues.variables) ||
694
+ !checkDataCompleteness(qryValues.data, query)
695
+ )
696
+ ) {
697
+ const cachedResult = fetchCachedData(query, variablesKey, updateObservers);
698
+ if (cachedResult) {
699
+ setQryValues({
700
+ ...qryValues,
701
+ variables,
702
+ data: cachedResult,
703
+ error: null,
704
+ loading: false, // IMPORTANT: must be false here
705
+ lastUpdatedCount: updatedCount || 0,
706
+ });
707
+
708
+ if (forceRefetch && !qryValues.loading) {
709
+ doQuery();
710
+ // console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
711
+ // console.log('::', variablesKey, skip, updatedCount);
712
+ }
713
+
714
+ } else if (!qryValues.loading) {
715
+ // doLog(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
716
+ doQuery();
717
+ }
718
+ }
719
+ }, [variablesKey, skip, updatedCount]);
720
+
721
+ // Refetch when the app reconnects and has no data
722
+
723
+ const withoutData = qryValues.data === null;
724
+ const reconnectedWithoutData = !skip && withoutData && !qryValues.loading && connectedToServer;
725
+
726
+ useEffect(() => {
727
+ if (connectedToServer && screenIsFocused && !skip) {
728
+ const now = Date.now();
729
+
730
+ let timeDiff, timeThresh;
731
+ if (reconnectedWithoutData) {
732
+ timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : Infinity;
733
+ timeThresh = 5000;
734
+ } else {
735
+ timeDiff = tracker.current.reconnectedAt ? now - tracker.current.reconnectedAt : -Infinity;
736
+ timeThresh = QUERY_EXPIRE_TIMES[queryName] || QUERY_EXPIRE_TIMES.__default;
737
+ }
738
+
739
+ // console.log('>>', queryName, timeDiff, timeThresh);
740
+
741
+ if (
742
+ tracker.current.init &&
743
+ timeDiff > timeThresh
744
+ ) {
745
+ // console.log('query again:', queryName, timeDiff);
746
+ // doLog(query, reconnectedWithoutData + ' / ' + skip + ' / ' + withoutData + ' / ' + !qryValues.loading);
747
+ tracker.current.reconnectedAt = now;
748
+ doQuery();
749
+ } else {
750
+ tracker.current.init = true;
751
+ }
752
+ }
753
+ }, [reconnectedWithoutData, screenIsFocused]);
754
+
755
+ const refetch = useCallback(() => {
756
+ return doQuery();
757
+ }, [doQuery]);
758
+
759
+ const fetchMore = useCallback(async(obj: GraphQLRequestOptions): Promise<any> => {
760
+ const result = await doQuery(obj?.variables);
761
+
762
+ if (result.error) {
763
+ return {
764
+ ...result,
765
+ error: normalizeServerError(result.error),
766
+ };
767
+ }
768
+
769
+ return result;
770
+ }, [doQuery]);
771
+
772
+ return {
773
+ ...qryValues,
774
+ data: loadDataFromCache(
775
+ qryValues.data,
776
+ query,
777
+ variablesKey,
778
+ cacheMap,
779
+ eagerFragmentKeyMap,
780
+ ),
781
+ queryName,
782
+ queryKey,
783
+ variablesKey,
784
+ refetch,
785
+ fetchMore,
786
+ updatedCount,
787
+ updateObservers,
788
+ connectedToServer,
789
+ screenIsFocused,
790
+ };
791
+ }