@jsb188/graphql 1.0.1 → 1.0.4

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