@jsb188/graphql 1.1.4 → 1.1.6

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.
Files changed (49) hide show
  1. package/cache/config.ts +13 -7
  2. package/cache/index.ts +355 -144
  3. package/gql/fragments/accountAuthFragments.ts +3 -9
  4. package/gql/fragments/accountFragments.ts +11 -0
  5. package/gql/fragments/actionFragments.ts +16 -0
  6. package/gql/fragments/logFragments.ts +75 -6
  7. package/gql/fragments/organizationFragments.ts +70 -4
  8. package/gql/fragments/otherFragments.ts +10 -8
  9. package/gql/fragments/productFragments.ts +63 -0
  10. package/gql/fragments/reportFragments.ts +47 -0
  11. package/gql/mutations/accountMutations.ts +31 -0
  12. package/gql/mutations/aiChatMutations.ts +1 -0
  13. package/gql/mutations/authMutations.ts +80 -22
  14. package/gql/mutations/index.ts +8 -0
  15. package/gql/mutations/logMutations.ts +56 -1
  16. package/gql/mutations/organizationMutations.ts +42 -0
  17. package/gql/mutations/otherMutations.ts +0 -17
  18. package/gql/mutations/userAuthMutations.ts +0 -116
  19. package/gql/queries/aiChatQueries.ts +4 -0
  20. package/gql/queries/appQueries.ts +2 -1
  21. package/gql/queries/index.ts +6 -0
  22. package/gql/queries/logQueries.ts +60 -11
  23. package/gql/queries/organizationQueries.ts +62 -1
  24. package/gql/queries/productQueries.ts +70 -0
  25. package/gql/queries/reportQueries.ts +60 -0
  26. package/hooks/index.ts +259 -113
  27. package/hooks/use-account-mtn.ts +68 -0
  28. package/hooks/use-aiChat-mtn.ts +112 -0
  29. package/hooks/use-aiChat-qry.ts +81 -10
  30. package/hooks/use-auth-mtn.ts +114 -63
  31. package/hooks/use-log-mtn.ts +85 -0
  32. package/hooks/use-log-qry.ts +71 -18
  33. package/hooks/use-organization-mtn.ts +105 -0
  34. package/hooks/use-organization-qry.ts +119 -15
  35. package/hooks/use-product-qry.ts +109 -0
  36. package/hooks/use-report-qry.ts +69 -0
  37. package/package.json +15 -25
  38. package/sse.ts +11 -0
  39. package/types.d.ts +1 -0
  40. package/gql/fragments/cardFragments.ts +0 -15
  41. package/gql/fragments/chatFragments.ts +0 -98
  42. package/gql/fragments/userAuthFragments.ts +0 -8
  43. package/gql/fragments/userFragments.ts +0 -69
  44. package/gql/mutations/chatMutations.ts +0 -116
  45. package/gql/mutations/userMutations.ts +0 -89
  46. package/gql/queries/cardQueries.ts +0 -24
  47. package/gql/queries/chatQueries.ts +0 -86
  48. package/gql/queries/otherQueries.ts +0 -12
  49. package/gql/queries/userQueries.ts +0 -104
package/hooks/index.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  import { getENVVariable } from '@jsb188/app';
2
2
  import type { ServerErrorObj, SimpleErrorType } from '@jsb188/app/types/app.d';
3
3
  import { normalizeServerError } from '@jsb188/app/utils/api';
4
- import { delay } from '@jsb188/app/utils/logic';
4
+ import { delay, makeVariablesKey } from '@jsb188/app/utils/logic';
5
5
  import { isServerErrorGQL } from '@jsb188/graphql/utils';
6
6
  import { useConnectedToServerValue, useFragmentObserverValue, useQueryObserverValue, useScreenIsFocusedValue, useSetFragmentObserver, useSetQueryObserver } from '@jsb188/react/states';
7
7
  import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
8
- import { checkDataCompleteness, fetchCachedData, loadDataFromCache, loadFragment, makeVariablesKey, removeStaleCache } from '../cache';
8
+ import { checkDataCompleteness, clearQueryResetStatus, fetchCachedData, getQueryRefreshTime, loadDataFromCache, loadFragment, removeStaleCache } from '../cache';
9
9
  import { QUERY_EXPIRE_TIMES } from '../cache/config';
10
- import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
11
10
  import { graphqlRequest } from '../client/request';
11
+ import type { AnyModalPopUpFn, GraphQLHandlers, GraphQLQueryOptions, OnCompletedGQLFn, OnErrorGQLFn, UpdateDataObserverArgs, UpdateObserversFn } from '../types';
12
12
 
13
13
 
14
14
  /**
@@ -34,6 +34,7 @@ type GraphQLMutationResult = {
34
34
  variables: Record<string, any> | null;
35
35
  saving: boolean;
36
36
  error: ServerErrorObj | null;
37
+ mutationCount: number;
37
38
  };
38
39
 
39
40
  type GraphQLMutation = [
@@ -41,7 +42,7 @@ type GraphQLMutation = [
41
42
  GraphQLMutationResult,
42
43
  GraphQLHandlers,
43
44
  UpdateObserversFn,
44
- React.MutableRefObject<boolean>
45
+ React.MutableRefObject<Record<string, any>>
45
46
  ];
46
47
 
47
48
  /**
@@ -61,6 +62,7 @@ type GraphQLQueryResult = {
61
62
  fetchMore: (obj: GraphQLRequestOptions) => Promise<any>;
62
63
  queryName: string;
63
64
  queryKey: string;
65
+ refreshTime: string;
64
66
  variablesKey: string;
65
67
  updatedCount: number;
66
68
  updateObservers: UpdateObserversFn;
@@ -126,34 +128,86 @@ export function useUpdateObservers(): UpdateObserversFn {
126
128
  export function useWatchQuery(
127
129
  query: any,
128
130
  variablesKey: string,
129
- ): [number, boolean] { // [updatedCount, forceRefetch]
131
+ lastUpdatedCount: number,
132
+ loading: boolean,
133
+ ) { // [updatedCount, forceRefetch, qryReset]
134
+
135
+ const qryObserver = useQueryObserverValue();
136
+ const [qryReset, setQryReset] = useState({
137
+ triggerTime: '',
138
+ refreshTime: '', // This value is fixed and never resets (this should be used as a tracker)
139
+ refreshTimeActive: '', // This value resets when loading starts
140
+ });
141
+
142
+ const queryWatcher = useMemo(() => {
143
+ if (qryObserver.name) {
144
+ const queryDefs = query.definitions.filter((d: any) => d.kind === 'OperationDefinition');
145
+ const queryName = queryDefs?.[0]?.name?.value;
146
+
147
+ if (queryName) {
148
+ const qryTriggerTime = getQueryRefreshTime(queryName, variablesKey);
130
149
 
131
- const queryObserver = useQueryObserverValue();
150
+ if (qryTriggerTime) {
151
+ clearQueryResetStatus(queryName, variablesKey);
152
+ return [lastUpdatedCount + 1, true, qryTriggerTime];
153
+ }
154
+ }
132
155
 
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));
156
+ const matchedQry = queryDefs
157
+ .find((d: any) =>
158
+ qryObserver.name.startsWith('#' + d.name.value) ||
159
+ ('#' + d.name.value + ':') === qryObserver.name
160
+ );
138
161
 
139
162
  if (!matchedQry) {
140
- return [0, false];
163
+ return [0, false, ''];
141
164
  }
142
165
 
143
- // console.log('matchedQry:', matchedQry);
144
- // console.log('queryObserver:', queryObserver);
166
+ const matchedQueryName = matchedQry.name.value;
167
+ const matchedQueryId = `#${matchedQueryName}:${variablesKey}`;
168
+ const forceRefetch = !!qryObserver.forceRefetch;
145
169
 
146
- const queryName = matchedQry.name.value;
147
- const queryId = `#${queryName}:${variablesKey}`;
170
+ let newUpdatedCount = qryObserver.name === matchedQueryId || forceRefetch ? qryObserver.count : 0;
171
+ if (forceRefetch) {
172
+ newUpdatedCount += 1;
173
+ }
148
174
 
149
- return [
150
- queryObserver.name === queryId ? queryObserver.count : 0,
151
- !!queryObserver.forceRefetch,
152
- ];
175
+ return [newUpdatedCount, forceRefetch, ''];
153
176
  }
154
177
 
155
- return [0, false];
156
- }, [queryObserver]);
178
+ return [0, false, ''];
179
+ }, [qryObserver]);
180
+
181
+ useEffect(() => {
182
+ if (!loading) {
183
+ if (qryReset.triggerTime && qryReset.refreshTimeActive === '') {
184
+ setQryReset((prev) => ({
185
+ ...prev,
186
+ refreshTime: qryReset.triggerTime,
187
+ refreshTimeActive: qryReset.triggerTime,
188
+ }));
189
+ } else if (queryWatcher[2] && queryWatcher[2] !== qryReset.triggerTime) {
190
+ setQryReset((prev) => ({
191
+ ...prev,
192
+ triggerTime: queryWatcher[2],
193
+ }));
194
+ }
195
+ } else if (qryReset.refreshTimeActive) {
196
+ setQryReset((prev) => ({
197
+ ...prev,
198
+ triggerTime: '',
199
+ refreshTimeActive: '',
200
+ }));
201
+ }
202
+ }, [queryWatcher[2], loading]);
203
+
204
+ // console.log('refreshTime:', refreshTime + queryWatcher[0]);
205
+
206
+ return {
207
+ updatedCount: queryWatcher[0],
208
+ forceRefetch: queryWatcher[1],
209
+ qryReset
210
+ };
157
211
  }
158
212
 
159
213
  /**
@@ -161,21 +215,48 @@ export function useWatchQuery(
161
215
  */
162
216
 
163
217
  export function useReactiveFragment(
164
- data_: any,
165
- observe: Array<string | string[]>,
166
- qryObsCount?: number,
218
+ data: any,
219
+ observe: Array<string | [string, string | null]>,
220
+ qryObsCount?: number | boolean,
167
221
  otherCheck?: (latestData: any, updatedKeys: any[]) => boolean,
168
222
  ignoreIDWarning?: boolean,
169
223
  // doTest?: boolean
170
224
  ) {
171
225
 
172
- const data = data_ || {};
173
226
  const fragmentObserver = useFragmentObserverValue();
174
227
  const frgObsCount = fragmentObserver.count;
175
- const [changedData, setChangedData] = useState<any>({
176
- fragmentUpdatedCount: frgObsCount,
177
- queryUpdatedCount: qryObsCount,
178
- data
228
+ const dataId = data?.id;
229
+
230
+ const [changedData, setChangedData] = useState<any>(() => {
231
+ // This allows initial data to *not* be null even when data param is null
232
+ let initialData = data;
233
+
234
+ observe.forEach((key) => {
235
+ const isMapped = Array.isArray(key);
236
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
237
+
238
+ if (fragmentData) {
239
+ if (isMapped) {
240
+ if (key[1]) {
241
+ initialData = {
242
+ ...initialData!,
243
+ [key[1]]: fragmentData,
244
+ };
245
+ }
246
+ } else {
247
+ initialData = {
248
+ ...initialData!,
249
+ ...fragmentData,
250
+ };
251
+ }
252
+ }
253
+ });
254
+
255
+ return {
256
+ fragmentUpdatedCount: frgObsCount,
257
+ queryUpdatedCount: qryObsCount,
258
+ data: initialData
259
+ };
179
260
  });
180
261
 
181
262
  if (getENVVariable('NODE_ENV') === 'development' && !ignoreIDWarning) {
@@ -184,26 +265,28 @@ export function useReactiveFragment(
184
265
  useEffect(() => {
185
266
  if (
186
267
  // getENVVariable('NODE_ENV') === 'development' &&
187
- data.id && changedData.data?.id &&
188
- data.id !== changedData.data?.id
268
+ dataId && changedData.data?.id &&
269
+ dataId !== changedData.data?.id
189
270
  ) {
190
- console.warn(`WARNING: useReactiveFragment() data.id changed from ${data.id} to ${changedData.data?.id}`);
271
+ console.warn(`WARNING: useReactiveFragment() data.id changed from ${dataId} to ${changedData.data?.id}`);
191
272
  console.warn('This can result in invalid merged data. Use key={id} to avoid this error.');
192
273
  }
193
274
  }, [changedData.data?.id]);
194
275
  }
195
276
 
196
277
  useEffect(() => {
197
- // NOTE: I tried this with effect()
278
+
279
+ // NOTE: I tried this with Preact's effect()
198
280
  // But that caused the render to happen 3 times more, I don't know why.
199
281
  // I only solved it by using useEffect()
200
282
  const idsChanged = (
201
- changedData.data.id !== data.id ||
283
+ !dataId ||
284
+ changedData.data?.id !== dataId ||
202
285
  (
203
286
  // This is absolutely needed for the chat clientId system to work properly;
204
287
  // Otherwise messages will be stuck in "not sent" state.
205
- changedData.data.clientId &&
206
- changedData.data.clientId !== data.clientId
288
+ changedData.data?.clientId &&
289
+ changedData.data?.clientId !== data.clientId
207
290
  )
208
291
  );
209
292
 
@@ -220,48 +303,52 @@ export function useReactiveFragment(
220
303
  )
221
304
  ) {
222
305
 
223
- // if (doTest) {
224
- // console.log('DO TEST:');
225
- // console.log(observe);
226
- // console.log(fragmentObserver);
227
- // }
306
+ const dataUpdated = (
307
+ idsChanged ||
308
+ forceReactive ||
309
+ observe.some((key) => {
310
+ const isMapped = Array.isArray(key);
311
+ return isMapped ? fragmentObserver.list.includes(key[0]) : fragmentObserver.list.includes(key);
312
+ })
313
+ )
228
314
 
229
315
  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;
316
+ if (dataUpdated) {
317
+ for (const key of observe) {
318
+ const isMapped = Array.isArray(key);
319
+
320
+ if (key) {
321
+ if (!newData) {
322
+ if (idsChanged) {
323
+ newData = data;
324
+ } else if (data) {
325
+ newData = {
326
+ ...data,
327
+ ...changedData.data,
328
+ };
329
+ } else {
330
+ newData = changedData.data;
331
+ }
250
332
  }
251
- }
252
333
 
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
- };
334
+ const fragmentData = loadFragment(isMapped ? key[0] : key);
335
+ // console.log('fragmentKey', key);
336
+ // console.log('fragmentData', fragmentData);
337
+
338
+ if (fragmentData) {
339
+ if (isMapped) {
340
+ if (key[1]) {
341
+ newData = {
342
+ ...newData,
343
+ [key[1]]: fragmentData,
344
+ };
345
+ }
346
+ } else {
347
+ newData = {
348
+ ...newData,
349
+ ...fragmentData,
350
+ };
351
+ }
265
352
  }
266
353
  }
267
354
  }
@@ -275,7 +362,7 @@ export function useReactiveFragment(
275
362
  });
276
363
  }
277
364
  }
278
- }, [data.id, qryObsCount, frgObsCount]);
365
+ }, [dataId, qryObsCount, frgObsCount]);
279
366
 
280
367
  // This is not needed now, I think
281
368
  // useEffect(() => {
@@ -291,7 +378,7 @@ export function useReactiveFragment(
291
378
  // }
292
379
  // }, [updateQueryCount]);
293
380
 
294
- return changedData.data;
381
+ return changedData.data ?? null;
295
382
  }
296
383
 
297
384
  /**
@@ -384,19 +471,27 @@ export function useMutation(
384
471
  // But bring it back if you want ability to "cancel"
385
472
  // const controller = useRef();
386
473
 
387
- const mounted = useRef(true);
474
+ const tracker = useRef({
475
+ mounted: true,
476
+ timer: null as NodeJS.Timeout | null,
477
+ });
478
+
388
479
  const [mtnValues, setMtnValues] = useState({
389
480
  variables: null as Record<string, any> | null,
390
481
  saving: false,
391
482
  data: null,
392
- error: initialError || null as ServerErrorObj | null
483
+ error: initialError || null as ServerErrorObj | null,
484
+ mutationCount: 0,
393
485
  });
394
486
 
395
487
  // Mounted hook
396
488
 
397
489
  useEffect(() => {
398
490
  return () => {
399
- mounted.current = false;
491
+ tracker.current.mounted = false;
492
+ if (tracker.current.timer) {
493
+ clearTimeout(tracker.current.timer);
494
+ }
400
495
  };
401
496
  }, []);
402
497
 
@@ -429,9 +524,10 @@ export function useMutation(
429
524
  {
430
525
  openModalPopUp: retryCount >= triedCount ? openModalPopUp : null,
431
526
  onCompleted: (data: any | null, error: ServerErrorObj | null) => {
432
- if (mounted.current) {
527
+ if (tracker.current.mounted) {
433
528
  setMtnValues({
434
529
  ...mtnValues,
530
+ mutationCount: mtnValues.mutationCount + 1,
435
531
  saving: false,
436
532
  data: data.data || null,
437
533
  error,
@@ -439,14 +535,14 @@ export function useMutation(
439
535
  }
440
536
 
441
537
  if (data.data) {
442
- if (onCompleted && (mounted.current || !checkMountedBeforeCallback)) {
538
+ if (onCompleted && (tracker.current.mounted || !checkMountedBeforeCallback)) {
443
539
  // Do separate {mounted.current} check from outside
444
540
  onCompleted(data.data, error, graphqlOptions?.variables);
445
541
  }
446
542
  }
447
543
  },
448
544
  onError: (error: ServerErrorObj | null) => {
449
- if (mounted.current) {
545
+ if (tracker.current.mounted) {
450
546
  setMtnValues({
451
547
  ...mtnValues,
452
548
  saving: retryCount > triedCount,
@@ -454,7 +550,7 @@ export function useMutation(
454
550
  });
455
551
  }
456
552
 
457
- if (onError && retryCount <= triedCount && (mounted.current || !checkMountedBeforeCallback)) {
553
+ if (onError && retryCount <= triedCount && (tracker.current.mounted || !checkMountedBeforeCallback)) {
458
554
  onError(error, graphqlOptions?.variables);
459
555
  }
460
556
  },
@@ -486,13 +582,13 @@ export function useMutation(
486
582
  };
487
583
 
488
584
  const mtnHandlers: GraphQLHandlers = {
489
- resetErrors: function () {
585
+ resetErrors: () => {
490
586
  setMtnValues({
491
587
  ...mtnValues,
492
588
  error: null,
493
589
  });
494
590
  },
495
- setError: function (errorObj: SimpleErrorType) {
591
+ setError: (errorObj: SimpleErrorType) => {
496
592
  setMtnValues({
497
593
  ...mtnValues,
498
594
  error: {
@@ -502,21 +598,32 @@ export function useMutation(
502
598
  },
503
599
  });
504
600
  },
505
- refetch: function () {
601
+ refetch: () => {
506
602
  const lastVariables = mtnValues.variables;
507
603
  return doMutate(lastVariables ? { variables: lastVariables } : undefined);
508
604
  },
605
+ setSaving: (nextSaving: boolean, resetInMS?: number) => {
606
+ setMtnValues({
607
+ ...mtnValues,
608
+ saving: nextSaving,
609
+ });
610
+
611
+ if (nextSaving && resetInMS) {
612
+ if (tracker.current.timer) {
613
+ clearTimeout(tracker.current.timer);
614
+ }
615
+
616
+ tracker.current.timer = setTimeout(() => {
617
+ setMtnValues({
618
+ ...mtnValues,
619
+ saving: false,
620
+ });
621
+ }, resetInMS);
622
+ }
623
+ }
509
624
  };
510
625
 
511
- // useEffect(() => {
512
- // return () => {
513
- // if (controller.current) {
514
- // controller.current.abort();
515
- // }
516
- // };
517
- // }, []);
518
-
519
- return [doMutate, mtnValues, mtnHandlers, updateObservers, mounted];
626
+ return [doMutate, mtnValues, mtnHandlers, updateObservers, tracker];
520
627
  }
521
628
 
522
629
  /**
@@ -527,12 +634,11 @@ export function useQuery(
527
634
  query: any,
528
635
  options?: GraphQLQueryOptions,
529
636
  ): GraphQLQueryResult {
530
- const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap } = options || {};
637
+ const { onCompleted, onError, openModalPopUp, variables, cacheMap, skip, eagerFragmentKeyMap, doTest } = options || {};
531
638
  const variablesKey = makeVariablesKey(variables);
532
639
  const connectedToServer = useConnectedToServerValue();
533
640
  const screenIsFocused = useScreenIsFocusedValue();
534
641
  const updateObservers = useUpdateObservers();
535
- const [updatedCount, forceRefetch] = useWatchQuery(query, variablesKey);
536
642
 
537
643
  // useQuery() assumes query is a single graphql query (and not a multi/chain)
538
644
  // Multiple queries can be chained using this hook,
@@ -544,6 +650,7 @@ export function useQuery(
544
650
  unique: null as string | null,
545
651
  abortCtrl: null as AbortController | null,
546
652
  reconnectedAt: null as number | null,
653
+ json: '',
547
654
  init: false
548
655
  });
549
656
 
@@ -554,16 +661,25 @@ export function useQuery(
554
661
  variables,
555
662
  loading: false,
556
663
  error: null as ServerErrorObj | null,
557
- lastUpdatedCount: 0
664
+ lastUpdatedCount: 0,
665
+ lastRefreshTriggerTime: '',
558
666
  });
559
667
 
668
+ const { updatedCount, forceRefetch, qryReset: { triggerTime, refreshTime } } = useWatchQuery(
669
+ query,
670
+ variablesKey,
671
+ qryValues.lastUpdatedCount,
672
+ qryValues.loading
673
+ );
674
+
675
+ const [queryOutput, setQueryOutput] = useState({ queryKey, refreshTime, data: null });
676
+
560
677
  // Query function for the client
561
678
  // NOTE: useQuery() assumes {query} and {options} will *never* change, except for {options.variables}
562
679
 
563
680
  const doQuery = async (queryVariables?: any, triedCount: number = 0) => {
564
681
 
565
682
  const currentHookId = QRY_TRACKER.get(queryKey);
566
-
567
683
  if (!currentHookId) {
568
684
  QRY_TRACKER.set(queryKey, tracker.current.unique);
569
685
  } else if (currentHookId) {
@@ -673,7 +789,12 @@ export function useQuery(
673
789
 
674
790
  return () => {
675
791
  unsetQueryTracker(queryKey, tracker.current.unique);
792
+ };
793
+ }, [queryKey]);
676
794
 
795
+
796
+ useEffect(() => {
797
+ return () => {
677
798
  if (tracker.current.abortCtrl) {
678
799
  // console.log('UMOUNTED:', queryKey, tracker.current.unique);
679
800
  tracker.current.abortCtrl.abort({
@@ -682,13 +803,18 @@ export function useQuery(
682
803
  });
683
804
  }
684
805
  };
685
- }, [queryKey]);
806
+ }, []);
686
807
 
687
808
  // Refetch when variables, skip status or query observer changes
688
809
 
810
+ // const isTest = queryName === 'logEntries';
811
+
689
812
  useEffect(() => {
813
+ // isTest && console.log('useQuery check:', refreshTime, updatedCount, qryValues.lastUpdatedCount);
814
+
690
815
  if (
691
816
  !skip && (
817
+ (triggerTime && triggerTime !== qryValues.lastRefreshTriggerTime) ||
692
818
  updatedCount !== qryValues.lastUpdatedCount ||
693
819
  variablesKey !== makeVariablesKey(qryValues.variables) ||
694
820
  !checkDataCompleteness(qryValues.data, query)
@@ -702,21 +828,22 @@ export function useQuery(
702
828
  data: cachedResult,
703
829
  error: null,
704
830
  loading: false, // IMPORTANT: must be false here
831
+ lastRefreshTriggerTime: triggerTime,
705
832
  lastUpdatedCount: updatedCount || 0,
706
833
  });
707
834
 
708
835
  if (forceRefetch && !qryValues.loading) {
709
836
  doQuery();
710
- // console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
837
+ // isTest && console.log('FORCE REFETCH AT:', query.definitions[0].name.value);
711
838
  // console.log('::', variablesKey, skip, updatedCount);
712
839
  }
713
840
 
714
841
  } else if (!qryValues.loading) {
715
- // doLog(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
842
+ // isTest && console.log(query, '>>>>> $0|' + variablesKey + skip + updatedCount + '|');
716
843
  doQuery();
717
844
  }
718
845
  }
719
- }, [variablesKey, skip, updatedCount]);
846
+ }, [variablesKey, skip, updatedCount, triggerTime]);
720
847
 
721
848
  // Refetch when the app reconnects and has no data
722
849
 
@@ -767,19 +894,38 @@ export function useQuery(
767
894
  }
768
895
 
769
896
  return result;
770
- }, [doQuery]);
897
+ }, [doQuery, skip]);
898
+
899
+ const queryData = loadDataFromCache(
900
+ qryValues.data,
901
+ query,
902
+ variablesKey,
903
+ cacheMap,
904
+ eagerFragmentKeyMap,
905
+ );
906
+
907
+ useEffect(() => {
908
+ const jsonStr = queryKey + '|' + JSON.stringify(queryData[queryName]);
909
+ if (tracker.current.json === jsonStr) {
910
+ return;
911
+ }
912
+
913
+ tracker.current.json = jsonStr;
914
+
915
+ // This makes queryKey and data always in sync
916
+ setQueryOutput({
917
+ queryKey,
918
+ refreshTime,
919
+ data: queryData,
920
+ });
921
+ }, [queryData[queryName]]);
771
922
 
772
923
  return {
773
924
  ...qryValues,
774
- data: loadDataFromCache(
775
- qryValues.data,
776
- query,
777
- variablesKey,
778
- cacheMap,
779
- eagerFragmentKeyMap,
780
- ),
781
925
  queryName,
782
- queryKey,
926
+ queryKey: queryOutput.queryKey,
927
+ data: queryOutput.data || queryData,
928
+ refreshTime: queryOutput.refreshTime,
783
929
  variablesKey,
784
930
  refetch,
785
931
  fetchMore,
@@ -0,0 +1,68 @@
1
+ import type { UseMutationParams } from '@jsb188/graphql/types.d';
2
+ import { OpenModalPopUpFn, useCurrentAccount } from '@jsb188/react/states';
3
+ import { requestChangeEmailMtn, editAccountMtn } from '../gql/mutations/accountMutations';
4
+ import { useMutation } from './index';
5
+
6
+ /**
7
+ * Edit logged in user's account
8
+ */
9
+
10
+ export function useEditAccount(
11
+ params?: UseMutationParams | null,
12
+ openModalPopUp?: OpenModalPopUpFn
13
+ ) {
14
+
15
+ const { account, settings, dispatchApp } = useCurrentAccount();
16
+ const [editAccount, mtnValues, mtnHandlers] = useMutation(
17
+ editAccountMtn,
18
+ {
19
+ // checkMountedBeforeCallback: true,
20
+ openModalPopUp,
21
+ ...params,
22
+ onCompleted: (data, error) => {
23
+ params?.onCompleted?.(data, error);
24
+
25
+ const updatedData = data.editAccount;
26
+ if (updatedData) {
27
+ dispatchApp({
28
+ __type: 'APP_EDIT_ACCOUNT',
29
+ data: updatedData,
30
+ });
31
+ }
32
+ }
33
+ },
34
+ );
35
+
36
+ return {
37
+ account,
38
+ settings,
39
+ editAccount,
40
+ ...mtnValues,
41
+ ...mtnHandlers,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Change logged in user's e-mail address
47
+ */
48
+
49
+ export function useRequestChangeEmail(
50
+ params?: UseMutationParams | null,
51
+ openModalPopUp?: OpenModalPopUpFn
52
+ ) {
53
+
54
+ const [requestChangeEmail, mtnValues, mtnHandlers] = useMutation(
55
+ requestChangeEmailMtn,
56
+ {
57
+ // checkMountedBeforeCallback: true,
58
+ openModalPopUp,
59
+ ...params,
60
+ },
61
+ );
62
+
63
+ return {
64
+ requestChangeEmail,
65
+ ...mtnValues,
66
+ ...mtnHandlers,
67
+ };
68
+ }