@tanstack/react-query 4.2.1 → 4.3.0-beta.0

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 (103) hide show
  1. package/build/{types/packages/react-query/src → lib}/Hydrate.d.ts +0 -0
  2. package/build/{types/packages/react-query/src → lib}/QueryClientProvider.d.ts +0 -0
  3. package/build/{types/packages/react-query/src → lib}/QueryErrorResetBoundary.d.ts +0 -0
  4. package/build/{types/packages/react-query/src → lib}/index.d.ts +0 -0
  5. package/build/lib/index.js +625 -0
  6. package/build/lib/index.js.map +1 -0
  7. package/build/lib/index.mjs +579 -0
  8. package/build/lib/index.mjs.map +1 -0
  9. package/build/{types/packages/react-query/src → lib}/isRestoring.d.ts +0 -0
  10. package/build/{types/packages/react-query/src → lib}/reactBatchedUpdates.d.ts +0 -0
  11. package/build/{types/packages/react-query/src → lib}/reactBatchedUpdates.native.d.ts +0 -0
  12. package/build/{types/packages/react-query/src → lib}/setBatchUpdatesFn.d.ts +0 -0
  13. package/build/{types/packages/react-query/src → lib}/types.d.ts +0 -0
  14. package/build/{types/packages/react-query/src → lib}/useBaseQuery.d.ts +0 -0
  15. package/build/{types/packages/react-query/src → lib}/useInfiniteQuery.d.ts +0 -0
  16. package/build/{types/packages/react-query/src → lib}/useIsFetching.d.ts +0 -0
  17. package/build/{types/packages/react-query/src → lib}/useIsMutating.d.ts +0 -0
  18. package/build/{types/packages/react-query/src → lib}/useMutation.d.ts +0 -0
  19. package/build/{types/packages/react-query/src → lib}/useQueries.d.ts +0 -0
  20. package/build/{types/packages/react-query/src → lib}/useQuery.d.ts +0 -0
  21. package/build/lib/useSyncExternalStore.d.ts +1 -0
  22. package/build/lib/useSyncExternalStore.native.d.ts +1 -0
  23. package/build/{types/packages/react-query/src → lib}/utils.d.ts +0 -0
  24. package/build/umd/index.development.js +272 -9
  25. package/build/umd/index.development.js.map +1 -1
  26. package/build/umd/index.production.js +3 -2
  27. package/build/umd/index.production.js.map +1 -1
  28. package/package.json +18 -15
  29. package/src/useBaseQuery.ts +1 -1
  30. package/src/useIsFetching.ts +1 -1
  31. package/src/useIsMutating.ts +1 -1
  32. package/src/useMutation.ts +1 -1
  33. package/src/useQueries.ts +1 -1
  34. package/src/useSyncExternalStore.native.ts +3 -0
  35. package/src/useSyncExternalStore.ts +2 -0
  36. package/build/cjs/query-core/build/esm/index.js +0 -3125
  37. package/build/cjs/query-core/build/esm/index.js.map +0 -1
  38. package/build/cjs/react-query/src/Hydrate.js +0 -66
  39. package/build/cjs/react-query/src/Hydrate.js.map +0 -1
  40. package/build/cjs/react-query/src/QueryClientProvider.js +0 -96
  41. package/build/cjs/react-query/src/QueryClientProvider.js.map +0 -1
  42. package/build/cjs/react-query/src/QueryErrorResetBoundary.js +0 -67
  43. package/build/cjs/react-query/src/QueryErrorResetBoundary.js.map +0 -1
  44. package/build/cjs/react-query/src/index.js +0 -64
  45. package/build/cjs/react-query/src/index.js.map +0 -1
  46. package/build/cjs/react-query/src/isRestoring.js +0 -43
  47. package/build/cjs/react-query/src/isRestoring.js.map +0 -1
  48. package/build/cjs/react-query/src/useBaseQuery.js +0 -117
  49. package/build/cjs/react-query/src/useBaseQuery.js.map +0 -1
  50. package/build/cjs/react-query/src/useInfiniteQuery.js +0 -24
  51. package/build/cjs/react-query/src/useInfiniteQuery.js.map +0 -1
  52. package/build/cjs/react-query/src/useIsFetching.js +0 -50
  53. package/build/cjs/react-query/src/useIsFetching.js.map +0 -1
  54. package/build/cjs/react-query/src/useIsMutating.js +0 -50
  55. package/build/cjs/react-query/src/useIsMutating.js.map +0 -1
  56. package/build/cjs/react-query/src/useMutation.js +0 -68
  57. package/build/cjs/react-query/src/useMutation.js.map +0 -1
  58. package/build/cjs/react-query/src/useQueries.js +0 -71
  59. package/build/cjs/react-query/src/useQueries.js.map +0 -1
  60. package/build/cjs/react-query/src/useQuery.js +0 -24
  61. package/build/cjs/react-query/src/useQuery.js.map +0 -1
  62. package/build/cjs/react-query/src/utils.js +0 -25
  63. package/build/cjs/react-query/src/utils.js.map +0 -1
  64. package/build/esm/index.js +0 -3383
  65. package/build/esm/index.js.map +0 -1
  66. package/build/stats-html.html +0 -2689
  67. package/build/stats.json +0 -666
  68. package/build/types/packages/query-core/src/focusManager.d.ts +0 -16
  69. package/build/types/packages/query-core/src/hydration.d.ts +0 -34
  70. package/build/types/packages/query-core/src/index.d.ts +0 -20
  71. package/build/types/packages/query-core/src/infiniteQueryBehavior.d.ts +0 -15
  72. package/build/types/packages/query-core/src/infiniteQueryObserver.d.ts +0 -18
  73. package/build/types/packages/query-core/src/logger.d.ts +0 -8
  74. package/build/types/packages/query-core/src/mutation.d.ts +0 -70
  75. package/build/types/packages/query-core/src/mutationCache.d.ts +0 -57
  76. package/build/types/packages/query-core/src/mutationObserver.d.ts +0 -23
  77. package/build/types/packages/query-core/src/notifyManager.d.ts +0 -18
  78. package/build/types/packages/query-core/src/onlineManager.d.ts +0 -16
  79. package/build/types/packages/query-core/src/queriesObserver.d.ts +0 -23
  80. package/build/types/packages/query-core/src/query.d.ts +0 -119
  81. package/build/types/packages/query-core/src/queryCache.d.ts +0 -64
  82. package/build/types/packages/query-core/src/queryClient.d.ts +0 -65
  83. package/build/types/packages/query-core/src/queryObserver.d.ts +0 -61
  84. package/build/types/packages/query-core/src/removable.d.ts +0 -9
  85. package/build/types/packages/query-core/src/retryer.d.ts +0 -33
  86. package/build/types/packages/query-core/src/subscribable.d.ts +0 -10
  87. package/build/types/packages/query-core/src/types.d.ts +0 -419
  88. package/build/types/packages/query-core/src/utils.d.ts +0 -99
  89. package/build/types/packages/react-query/src/__tests__/Hydrate.test.d.ts +0 -1
  90. package/build/types/packages/react-query/src/__tests__/QueryClientProvider.test.d.ts +0 -1
  91. package/build/types/packages/react-query/src/__tests__/QueryResetErrorBoundary.test.d.ts +0 -6
  92. package/build/types/packages/react-query/src/__tests__/ssr-hydration.test.d.ts +0 -1
  93. package/build/types/packages/react-query/src/__tests__/ssr.test.d.ts +0 -4
  94. package/build/types/packages/react-query/src/__tests__/suspense.test.d.ts +0 -1
  95. package/build/types/packages/react-query/src/__tests__/useInfiniteQuery.test.d.ts +0 -1
  96. package/build/types/packages/react-query/src/__tests__/useIsFetching.test.d.ts +0 -1
  97. package/build/types/packages/react-query/src/__tests__/useIsMutating.test.d.ts +0 -1
  98. package/build/types/packages/react-query/src/__tests__/useMutation.test.d.ts +0 -1
  99. package/build/types/packages/react-query/src/__tests__/useQueries.test.d.ts +0 -1
  100. package/build/types/packages/react-query/src/__tests__/useQuery.test.d.ts +0 -1
  101. package/build/types/packages/react-query/src/__tests__/useQuery.types.test.d.ts +0 -2
  102. package/build/types/packages/react-query/src/__tests__/utils.d.ts +0 -8
  103. package/build/types/tests/utils.d.ts +0 -24
@@ -1,3125 +0,0 @@
1
- /**
2
- * react-query
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- /**
16
- * query-core
17
- *
18
- * Copyright (c) TanStack
19
- *
20
- * This source code is licensed under the MIT license found in the
21
- * LICENSE.md file in the root directory of this source tree.
22
- *
23
- * @license MIT
24
- */
25
- class Subscribable {
26
- constructor() {
27
- this.listeners = [];
28
- this.subscribe = this.subscribe.bind(this);
29
- }
30
-
31
- subscribe(listener) {
32
- this.listeners.push(listener);
33
- this.onSubscribe();
34
- return () => {
35
- this.listeners = this.listeners.filter(x => x !== listener);
36
- this.onUnsubscribe();
37
- };
38
- }
39
-
40
- hasListeners() {
41
- return this.listeners.length > 0;
42
- }
43
-
44
- onSubscribe() {// Do nothing
45
- }
46
-
47
- onUnsubscribe() {// Do nothing
48
- }
49
-
50
- }
51
-
52
- // TYPES
53
- // UTILS
54
- const isServer = typeof window === 'undefined';
55
- function noop() {
56
- return undefined;
57
- }
58
- function functionalUpdate(updater, input) {
59
- return typeof updater === 'function' ? updater(input) : updater;
60
- }
61
- function isValidTimeout(value) {
62
- return typeof value === 'number' && value >= 0 && value !== Infinity;
63
- }
64
- function difference(array1, array2) {
65
- return array1.filter(x => array2.indexOf(x) === -1);
66
- }
67
- function replaceAt(array, index, value) {
68
- const copy = array.slice(0);
69
- copy[index] = value;
70
- return copy;
71
- }
72
- function timeUntilStale(updatedAt, staleTime) {
73
- return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
74
- }
75
- function parseQueryArgs(arg1, arg2, arg3) {
76
- if (!isQueryKey(arg1)) {
77
- return arg1;
78
- }
79
-
80
- if (typeof arg2 === 'function') {
81
- return { ...arg3,
82
- queryKey: arg1,
83
- queryFn: arg2
84
- };
85
- }
86
-
87
- return { ...arg2,
88
- queryKey: arg1
89
- };
90
- }
91
- function parseMutationArgs(arg1, arg2, arg3) {
92
- if (isQueryKey(arg1)) {
93
- if (typeof arg2 === 'function') {
94
- return { ...arg3,
95
- mutationKey: arg1,
96
- mutationFn: arg2
97
- };
98
- }
99
-
100
- return { ...arg2,
101
- mutationKey: arg1
102
- };
103
- }
104
-
105
- if (typeof arg1 === 'function') {
106
- return { ...arg2,
107
- mutationFn: arg1
108
- };
109
- }
110
-
111
- return { ...arg1
112
- };
113
- }
114
- function parseFilterArgs(arg1, arg2, arg3) {
115
- return isQueryKey(arg1) ? [{ ...arg2,
116
- queryKey: arg1
117
- }, arg3] : [arg1 || {}, arg2];
118
- }
119
- function parseMutationFilterArgs(arg1, arg2, arg3) {
120
- return isQueryKey(arg1) ? [{ ...arg2,
121
- mutationKey: arg1
122
- }, arg3] : [arg1 || {}, arg2];
123
- }
124
- function matchQuery(filters, query) {
125
- const {
126
- type = 'all',
127
- exact,
128
- fetchStatus,
129
- predicate,
130
- queryKey,
131
- stale
132
- } = filters;
133
-
134
- if (isQueryKey(queryKey)) {
135
- if (exact) {
136
- if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
137
- return false;
138
- }
139
- } else if (!partialMatchKey(query.queryKey, queryKey)) {
140
- return false;
141
- }
142
- }
143
-
144
- if (type !== 'all') {
145
- const isActive = query.isActive();
146
-
147
- if (type === 'active' && !isActive) {
148
- return false;
149
- }
150
-
151
- if (type === 'inactive' && isActive) {
152
- return false;
153
- }
154
- }
155
-
156
- if (typeof stale === 'boolean' && query.isStale() !== stale) {
157
- return false;
158
- }
159
-
160
- if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
161
- return false;
162
- }
163
-
164
- if (predicate && !predicate(query)) {
165
- return false;
166
- }
167
-
168
- return true;
169
- }
170
- function matchMutation(filters, mutation) {
171
- const {
172
- exact,
173
- fetching,
174
- predicate,
175
- mutationKey
176
- } = filters;
177
-
178
- if (isQueryKey(mutationKey)) {
179
- if (!mutation.options.mutationKey) {
180
- return false;
181
- }
182
-
183
- if (exact) {
184
- if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
185
- return false;
186
- }
187
- } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
188
- return false;
189
- }
190
- }
191
-
192
- if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
193
- return false;
194
- }
195
-
196
- if (predicate && !predicate(mutation)) {
197
- return false;
198
- }
199
-
200
- return true;
201
- }
202
- function hashQueryKeyByOptions(queryKey, options) {
203
- const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
204
- return hashFn(queryKey);
205
- }
206
- /**
207
- * Default query keys hash function.
208
- * Hashes the value into a stable hash.
209
- */
210
-
211
- function hashQueryKey(queryKey) {
212
- return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
213
- result[key] = val[key];
214
- return result;
215
- }, {}) : val);
216
- }
217
- /**
218
- * Checks if key `b` partially matches with key `a`.
219
- */
220
-
221
- function partialMatchKey(a, b) {
222
- return partialDeepEqual(a, b);
223
- }
224
- /**
225
- * Checks if `b` partially matches with `a`.
226
- */
227
-
228
- function partialDeepEqual(a, b) {
229
- if (a === b) {
230
- return true;
231
- }
232
-
233
- if (typeof a !== typeof b) {
234
- return false;
235
- }
236
-
237
- if (a && b && typeof a === 'object' && typeof b === 'object') {
238
- return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]));
239
- }
240
-
241
- return false;
242
- }
243
- /**
244
- * This function returns `a` if `b` is deeply equal.
245
- * If not, it will replace any deeply equal children of `b` with those of `a`.
246
- * This can be used for structural sharing between JSON values for example.
247
- */
248
-
249
- function replaceEqualDeep(a, b) {
250
- if (a === b) {
251
- return a;
252
- }
253
-
254
- const array = isPlainArray(a) && isPlainArray(b);
255
-
256
- if (array || isPlainObject(a) && isPlainObject(b)) {
257
- const aSize = array ? a.length : Object.keys(a).length;
258
- const bItems = array ? b : Object.keys(b);
259
- const bSize = bItems.length;
260
- const copy = array ? [] : {};
261
- let equalItems = 0;
262
-
263
- for (let i = 0; i < bSize; i++) {
264
- const key = array ? i : bItems[i];
265
- copy[key] = replaceEqualDeep(a[key], b[key]);
266
-
267
- if (copy[key] === a[key]) {
268
- equalItems++;
269
- }
270
- }
271
-
272
- return aSize === bSize && equalItems === aSize ? a : copy;
273
- }
274
-
275
- return b;
276
- }
277
- /**
278
- * Shallow compare objects. Only works with objects that always have the same properties.
279
- */
280
-
281
- function shallowEqualObjects(a, b) {
282
- if (a && !b || b && !a) {
283
- return false;
284
- }
285
-
286
- for (const key in a) {
287
- if (a[key] !== b[key]) {
288
- return false;
289
- }
290
- }
291
-
292
- return true;
293
- }
294
- function isPlainArray(value) {
295
- return Array.isArray(value) && value.length === Object.keys(value).length;
296
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
297
-
298
- function isPlainObject(o) {
299
- if (!hasObjectPrototype(o)) {
300
- return false;
301
- } // If has modified constructor
302
-
303
-
304
- const ctor = o.constructor;
305
-
306
- if (typeof ctor === 'undefined') {
307
- return true;
308
- } // If has modified prototype
309
-
310
-
311
- const prot = ctor.prototype;
312
-
313
- if (!hasObjectPrototype(prot)) {
314
- return false;
315
- } // If constructor does not have an Object-specific method
316
-
317
-
318
- if (!prot.hasOwnProperty('isPrototypeOf')) {
319
- return false;
320
- } // Most likely a plain Object
321
-
322
-
323
- return true;
324
- }
325
-
326
- function hasObjectPrototype(o) {
327
- return Object.prototype.toString.call(o) === '[object Object]';
328
- }
329
-
330
- function isQueryKey(value) {
331
- return Array.isArray(value);
332
- }
333
- function isError(value) {
334
- return value instanceof Error;
335
- }
336
- function sleep(timeout) {
337
- return new Promise(resolve => {
338
- setTimeout(resolve, timeout);
339
- });
340
- }
341
- /**
342
- * Schedules a microtask.
343
- * This can be useful to schedule state updates after rendering.
344
- */
345
-
346
- function scheduleMicrotask(callback) {
347
- sleep(0).then(callback);
348
- }
349
- function getAbortController() {
350
- if (typeof AbortController === 'function') {
351
- return new AbortController();
352
- }
353
- }
354
- function replaceData(prevData, data, options) {
355
- // Use prev data if an isDataEqual function is defined and returns `true`
356
- if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
357
- return prevData;
358
- } else if (typeof options.structuralSharing === 'function') {
359
- return options.structuralSharing(prevData, data);
360
- } else if (options.structuralSharing !== false) {
361
- // Structurally share data between prev and new data if needed
362
- return replaceEqualDeep(prevData, data);
363
- }
364
-
365
- return data;
366
- }
367
-
368
- class FocusManager extends Subscribable {
369
- constructor() {
370
- super();
371
-
372
- this.setup = onFocus => {
373
- // addEventListener does not exist in React Native, but window does
374
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
375
- if (!isServer && window.addEventListener) {
376
- const listener = () => onFocus(); // Listen to visibillitychange and focus
377
-
378
-
379
- window.addEventListener('visibilitychange', listener, false);
380
- window.addEventListener('focus', listener, false);
381
- return () => {
382
- // Be sure to unsubscribe if a new handler is set
383
- window.removeEventListener('visibilitychange', listener);
384
- window.removeEventListener('focus', listener);
385
- };
386
- }
387
- };
388
- }
389
-
390
- onSubscribe() {
391
- if (!this.cleanup) {
392
- this.setEventListener(this.setup);
393
- }
394
- }
395
-
396
- onUnsubscribe() {
397
- if (!this.hasListeners()) {
398
- var _this$cleanup;
399
-
400
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
401
- this.cleanup = undefined;
402
- }
403
- }
404
-
405
- setEventListener(setup) {
406
- var _this$cleanup2;
407
-
408
- this.setup = setup;
409
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
410
- this.cleanup = setup(focused => {
411
- if (typeof focused === 'boolean') {
412
- this.setFocused(focused);
413
- } else {
414
- this.onFocus();
415
- }
416
- });
417
- }
418
-
419
- setFocused(focused) {
420
- this.focused = focused;
421
-
422
- if (focused) {
423
- this.onFocus();
424
- }
425
- }
426
-
427
- onFocus() {
428
- this.listeners.forEach(listener => {
429
- listener();
430
- });
431
- }
432
-
433
- isFocused() {
434
- if (typeof this.focused === 'boolean') {
435
- return this.focused;
436
- } // document global can be unavailable in react native
437
-
438
-
439
- if (typeof document === 'undefined') {
440
- return true;
441
- }
442
-
443
- return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
444
- }
445
-
446
- }
447
- const focusManager = new FocusManager();
448
-
449
- class OnlineManager extends Subscribable {
450
- constructor() {
451
- super();
452
-
453
- this.setup = onOnline => {
454
- // addEventListener does not exist in React Native, but window does
455
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
456
- if (!isServer && window.addEventListener) {
457
- const listener = () => onOnline(); // Listen to online
458
-
459
-
460
- window.addEventListener('online', listener, false);
461
- window.addEventListener('offline', listener, false);
462
- return () => {
463
- // Be sure to unsubscribe if a new handler is set
464
- window.removeEventListener('online', listener);
465
- window.removeEventListener('offline', listener);
466
- };
467
- }
468
- };
469
- }
470
-
471
- onSubscribe() {
472
- if (!this.cleanup) {
473
- this.setEventListener(this.setup);
474
- }
475
- }
476
-
477
- onUnsubscribe() {
478
- if (!this.hasListeners()) {
479
- var _this$cleanup;
480
-
481
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
482
- this.cleanup = undefined;
483
- }
484
- }
485
-
486
- setEventListener(setup) {
487
- var _this$cleanup2;
488
-
489
- this.setup = setup;
490
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
491
- this.cleanup = setup(online => {
492
- if (typeof online === 'boolean') {
493
- this.setOnline(online);
494
- } else {
495
- this.onOnline();
496
- }
497
- });
498
- }
499
-
500
- setOnline(online) {
501
- this.online = online;
502
-
503
- if (online) {
504
- this.onOnline();
505
- }
506
- }
507
-
508
- onOnline() {
509
- this.listeners.forEach(listener => {
510
- listener();
511
- });
512
- }
513
-
514
- isOnline() {
515
- if (typeof this.online === 'boolean') {
516
- return this.online;
517
- }
518
-
519
- if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
520
- return true;
521
- }
522
-
523
- return navigator.onLine;
524
- }
525
-
526
- }
527
- const onlineManager = new OnlineManager();
528
-
529
- function defaultRetryDelay(failureCount) {
530
- return Math.min(1000 * 2 ** failureCount, 30000);
531
- }
532
-
533
- function canFetch(networkMode) {
534
- return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
535
- }
536
- class CancelledError {
537
- constructor(options) {
538
- this.revert = options == null ? void 0 : options.revert;
539
- this.silent = options == null ? void 0 : options.silent;
540
- }
541
-
542
- }
543
- function isCancelledError(value) {
544
- return value instanceof CancelledError;
545
- }
546
- function createRetryer(config) {
547
- let isRetryCancelled = false;
548
- let failureCount = 0;
549
- let isResolved = false;
550
- let continueFn;
551
- let promiseResolve;
552
- let promiseReject;
553
- const promise = new Promise((outerResolve, outerReject) => {
554
- promiseResolve = outerResolve;
555
- promiseReject = outerReject;
556
- });
557
-
558
- const cancel = cancelOptions => {
559
- if (!isResolved) {
560
- reject(new CancelledError(cancelOptions));
561
- config.abort == null ? void 0 : config.abort();
562
- }
563
- };
564
-
565
- const cancelRetry = () => {
566
- isRetryCancelled = true;
567
- };
568
-
569
- const continueRetry = () => {
570
- isRetryCancelled = false;
571
- };
572
-
573
- const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
574
-
575
- const resolve = value => {
576
- if (!isResolved) {
577
- isResolved = true;
578
- config.onSuccess == null ? void 0 : config.onSuccess(value);
579
- continueFn == null ? void 0 : continueFn();
580
- promiseResolve(value);
581
- }
582
- };
583
-
584
- const reject = value => {
585
- if (!isResolved) {
586
- isResolved = true;
587
- config.onError == null ? void 0 : config.onError(value);
588
- continueFn == null ? void 0 : continueFn();
589
- promiseReject(value);
590
- }
591
- };
592
-
593
- const pause = () => {
594
- return new Promise(continueResolve => {
595
- continueFn = value => {
596
- if (isResolved || !shouldPause()) {
597
- return continueResolve(value);
598
- }
599
- };
600
-
601
- config.onPause == null ? void 0 : config.onPause();
602
- }).then(() => {
603
- continueFn = undefined;
604
-
605
- if (!isResolved) {
606
- config.onContinue == null ? void 0 : config.onContinue();
607
- }
608
- });
609
- }; // Create loop function
610
-
611
-
612
- const run = () => {
613
- // Do nothing if already resolved
614
- if (isResolved) {
615
- return;
616
- }
617
-
618
- let promiseOrValue; // Execute query
619
-
620
- try {
621
- promiseOrValue = config.fn();
622
- } catch (error) {
623
- promiseOrValue = Promise.reject(error);
624
- }
625
-
626
- Promise.resolve(promiseOrValue).then(resolve).catch(error => {
627
- var _config$retry, _config$retryDelay;
628
-
629
- // Stop if the fetch is already resolved
630
- if (isResolved) {
631
- return;
632
- } // Do we need to retry the request?
633
-
634
-
635
- const retry = (_config$retry = config.retry) != null ? _config$retry : 3;
636
- const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
637
- const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
638
- const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
639
-
640
- if (isRetryCancelled || !shouldRetry) {
641
- // We are done if the query does not need to be retried
642
- reject(error);
643
- return;
644
- }
645
-
646
- failureCount++; // Notify on fail
647
-
648
- config.onFail == null ? void 0 : config.onFail(failureCount, error); // Delay
649
-
650
- sleep(delay) // Pause if the document is not visible or when the device is offline
651
- .then(() => {
652
- if (shouldPause()) {
653
- return pause();
654
- }
655
- }).then(() => {
656
- if (isRetryCancelled) {
657
- reject(error);
658
- } else {
659
- run();
660
- }
661
- });
662
- });
663
- }; // Start loop
664
-
665
-
666
- if (canFetch(config.networkMode)) {
667
- run();
668
- } else {
669
- pause().then(run);
670
- }
671
-
672
- return {
673
- promise,
674
- cancel,
675
- continue: () => {
676
- continueFn == null ? void 0 : continueFn();
677
- },
678
- cancelRetry,
679
- continueRetry
680
- };
681
- }
682
-
683
- const defaultLogger = console;
684
-
685
- function createNotifyManager() {
686
- let queue = [];
687
- let transactions = 0;
688
-
689
- let notifyFn = callback => {
690
- callback();
691
- };
692
-
693
- let batchNotifyFn = callback => {
694
- callback();
695
- };
696
-
697
- const batch = callback => {
698
- let result;
699
- transactions++;
700
-
701
- try {
702
- result = callback();
703
- } finally {
704
- transactions--;
705
-
706
- if (!transactions) {
707
- flush();
708
- }
709
- }
710
-
711
- return result;
712
- };
713
-
714
- const schedule = callback => {
715
- if (transactions) {
716
- queue.push(callback);
717
- } else {
718
- scheduleMicrotask(() => {
719
- notifyFn(callback);
720
- });
721
- }
722
- };
723
- /**
724
- * All calls to the wrapped function will be batched.
725
- */
726
-
727
-
728
- const batchCalls = callback => {
729
- return (...args) => {
730
- schedule(() => {
731
- callback(...args);
732
- });
733
- };
734
- };
735
-
736
- const flush = () => {
737
- const originalQueue = queue;
738
- queue = [];
739
-
740
- if (originalQueue.length) {
741
- scheduleMicrotask(() => {
742
- batchNotifyFn(() => {
743
- originalQueue.forEach(callback => {
744
- notifyFn(callback);
745
- });
746
- });
747
- });
748
- }
749
- };
750
- /**
751
- * Use this method to set a custom notify function.
752
- * This can be used to for example wrap notifications with `React.act` while running tests.
753
- */
754
-
755
-
756
- const setNotifyFunction = fn => {
757
- notifyFn = fn;
758
- };
759
- /**
760
- * Use this method to set a custom function to batch notifications together into a single tick.
761
- * By default React Query will use the batch function provided by ReactDOM or React Native.
762
- */
763
-
764
-
765
- const setBatchNotifyFunction = fn => {
766
- batchNotifyFn = fn;
767
- };
768
-
769
- return {
770
- batch,
771
- batchCalls,
772
- schedule,
773
- setNotifyFunction,
774
- setBatchNotifyFunction
775
- };
776
- } // SINGLETON
777
-
778
- const notifyManager = createNotifyManager();
779
-
780
- class Removable {
781
- destroy() {
782
- this.clearGcTimeout();
783
- }
784
-
785
- scheduleGc() {
786
- this.clearGcTimeout();
787
-
788
- if (isValidTimeout(this.cacheTime)) {
789
- this.gcTimeout = setTimeout(() => {
790
- this.optionalRemove();
791
- }, this.cacheTime);
792
- }
793
- }
794
-
795
- updateCacheTime(newCacheTime) {
796
- // Default to 5 minutes (Infinity for server-side) if no cache time is set
797
- this.cacheTime = Math.max(this.cacheTime || 0, newCacheTime != null ? newCacheTime : isServer ? Infinity : 5 * 60 * 1000);
798
- }
799
-
800
- clearGcTimeout() {
801
- if (this.gcTimeout) {
802
- clearTimeout(this.gcTimeout);
803
- this.gcTimeout = undefined;
804
- }
805
- }
806
-
807
- }
808
-
809
- // CLASS
810
- class Query extends Removable {
811
- constructor(config) {
812
- super();
813
- this.abortSignalConsumed = false;
814
- this.defaultOptions = config.defaultOptions;
815
- this.setOptions(config.options);
816
- this.observers = [];
817
- this.cache = config.cache;
818
- this.logger = config.logger || defaultLogger;
819
- this.queryKey = config.queryKey;
820
- this.queryHash = config.queryHash;
821
- this.initialState = config.state || getDefaultState$1(this.options);
822
- this.state = this.initialState;
823
- this.meta = config.meta;
824
- }
825
-
826
- setOptions(options) {
827
- this.options = { ...this.defaultOptions,
828
- ...options
829
- };
830
- this.meta = options == null ? void 0 : options.meta;
831
- this.updateCacheTime(this.options.cacheTime);
832
- }
833
-
834
- optionalRemove() {
835
- if (!this.observers.length && this.state.fetchStatus === 'idle') {
836
- this.cache.remove(this);
837
- }
838
- }
839
-
840
- setData(newData, options) {
841
- const data = replaceData(this.state.data, newData, this.options); // Set data and mark it as cached
842
-
843
- this.dispatch({
844
- data,
845
- type: 'success',
846
- dataUpdatedAt: options == null ? void 0 : options.updatedAt,
847
- manual: options == null ? void 0 : options.manual
848
- });
849
- return data;
850
- }
851
-
852
- setState(state, setStateOptions) {
853
- this.dispatch({
854
- type: 'setState',
855
- state,
856
- setStateOptions
857
- });
858
- }
859
-
860
- cancel(options) {
861
- var _this$retryer;
862
-
863
- const promise = this.promise;
864
- (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
865
- return promise ? promise.then(noop).catch(noop) : Promise.resolve();
866
- }
867
-
868
- destroy() {
869
- super.destroy();
870
- this.cancel({
871
- silent: true
872
- });
873
- }
874
-
875
- reset() {
876
- this.destroy();
877
- this.setState(this.initialState);
878
- }
879
-
880
- isActive() {
881
- return this.observers.some(observer => observer.options.enabled !== false);
882
- }
883
-
884
- isDisabled() {
885
- return this.getObserversCount() > 0 && !this.isActive();
886
- }
887
-
888
- isStale() {
889
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(observer => observer.getCurrentResult().isStale);
890
- }
891
-
892
- isStaleByTime(staleTime = 0) {
893
- return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
894
- }
895
-
896
- onFocus() {
897
- var _this$retryer2;
898
-
899
- const observer = this.observers.find(x => x.shouldFetchOnWindowFocus());
900
-
901
- if (observer) {
902
- observer.refetch({
903
- cancelRefetch: false
904
- });
905
- } // Continue fetch if currently paused
906
-
907
-
908
- (_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
909
- }
910
-
911
- onOnline() {
912
- var _this$retryer3;
913
-
914
- const observer = this.observers.find(x => x.shouldFetchOnReconnect());
915
-
916
- if (observer) {
917
- observer.refetch({
918
- cancelRefetch: false
919
- });
920
- } // Continue fetch if currently paused
921
-
922
-
923
- (_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
924
- }
925
-
926
- addObserver(observer) {
927
- if (this.observers.indexOf(observer) === -1) {
928
- this.observers.push(observer); // Stop the query from being garbage collected
929
-
930
- this.clearGcTimeout();
931
- this.cache.notify({
932
- type: 'observerAdded',
933
- query: this,
934
- observer
935
- });
936
- }
937
- }
938
-
939
- removeObserver(observer) {
940
- if (this.observers.indexOf(observer) !== -1) {
941
- this.observers = this.observers.filter(x => x !== observer);
942
-
943
- if (!this.observers.length) {
944
- // If the transport layer does not support cancellation
945
- // we'll let the query continue so the result can be cached
946
- if (this.retryer) {
947
- if (this.abortSignalConsumed) {
948
- this.retryer.cancel({
949
- revert: true
950
- });
951
- } else {
952
- this.retryer.cancelRetry();
953
- }
954
- }
955
-
956
- this.scheduleGc();
957
- }
958
-
959
- this.cache.notify({
960
- type: 'observerRemoved',
961
- query: this,
962
- observer
963
- });
964
- }
965
- }
966
-
967
- getObserversCount() {
968
- return this.observers.length;
969
- }
970
-
971
- invalidate() {
972
- if (!this.state.isInvalidated) {
973
- this.dispatch({
974
- type: 'invalidate'
975
- });
976
- }
977
- }
978
-
979
- fetch(options, fetchOptions) {
980
- var _this$options$behavio, _context$fetchOptions;
981
-
982
- if (this.state.fetchStatus !== 'idle') {
983
- if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) {
984
- // Silently cancel current fetch if the user wants to cancel refetches
985
- this.cancel({
986
- silent: true
987
- });
988
- } else if (this.promise) {
989
- var _this$retryer4;
990
-
991
- // make sure that retries that were potentially cancelled due to unmounts can continue
992
- (_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
993
-
994
- return this.promise;
995
- }
996
- } // Update config if passed, otherwise the config from the last execution is used
997
-
998
-
999
- if (options) {
1000
- this.setOptions(options);
1001
- } // Use the options from the first observer with a query function if no function is found.
1002
- // This can happen when the query is hydrated or created with setQueryData.
1003
-
1004
-
1005
- if (!this.options.queryFn) {
1006
- const observer = this.observers.find(x => x.options.queryFn);
1007
-
1008
- if (observer) {
1009
- this.setOptions(observer.options);
1010
- }
1011
- }
1012
-
1013
- if (!Array.isArray(this.options.queryKey)) {
1014
- if (process.env.NODE_ENV !== 'production') {
1015
- this.logger.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']");
1016
- }
1017
- }
1018
-
1019
- const abortController = getAbortController(); // Create query function context
1020
-
1021
- const queryFnContext = {
1022
- queryKey: this.queryKey,
1023
- pageParam: undefined,
1024
- meta: this.meta
1025
- }; // Adds an enumerable signal property to the object that
1026
- // which sets abortSignalConsumed to true when the signal
1027
- // is read.
1028
-
1029
- const addSignalProperty = object => {
1030
- Object.defineProperty(object, 'signal', {
1031
- enumerable: true,
1032
- get: () => {
1033
- if (abortController) {
1034
- this.abortSignalConsumed = true;
1035
- return abortController.signal;
1036
- }
1037
-
1038
- return undefined;
1039
- }
1040
- });
1041
- };
1042
-
1043
- addSignalProperty(queryFnContext); // Create fetch function
1044
-
1045
- const fetchFn = () => {
1046
- if (!this.options.queryFn) {
1047
- return Promise.reject('Missing queryFn');
1048
- }
1049
-
1050
- this.abortSignalConsumed = false;
1051
- return this.options.queryFn(queryFnContext);
1052
- }; // Trigger behavior hook
1053
-
1054
-
1055
- const context = {
1056
- fetchOptions,
1057
- options: this.options,
1058
- queryKey: this.queryKey,
1059
- state: this.state,
1060
- fetchFn,
1061
- meta: this.meta
1062
- };
1063
- addSignalProperty(context);
1064
- (_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch(context); // Store state in case the current fetch needs to be reverted
1065
-
1066
- this.revertState = this.state; // Set to fetching state if not already in it
1067
-
1068
- if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
1069
- var _context$fetchOptions2;
1070
-
1071
- this.dispatch({
1072
- type: 'fetch',
1073
- meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
1074
- });
1075
- }
1076
-
1077
- const onError = error => {
1078
- // Optimistically update state if needed
1079
- if (!(isCancelledError(error) && error.silent)) {
1080
- this.dispatch({
1081
- type: 'error',
1082
- error: error
1083
- });
1084
- }
1085
-
1086
- if (!isCancelledError(error)) {
1087
- var _this$cache$config$on, _this$cache$config;
1088
-
1089
- // Notify cache callback
1090
- (_this$cache$config$on = (_this$cache$config = this.cache.config).onError) == null ? void 0 : _this$cache$config$on.call(_this$cache$config, error, this);
1091
-
1092
- if (process.env.NODE_ENV !== 'production') {
1093
- this.logger.error(error);
1094
- }
1095
- }
1096
-
1097
- if (!this.isFetchingOptimistic) {
1098
- // Schedule query gc after fetching
1099
- this.scheduleGc();
1100
- }
1101
-
1102
- this.isFetchingOptimistic = false;
1103
- }; // Try to fetch the data
1104
-
1105
-
1106
- this.retryer = createRetryer({
1107
- fn: context.fetchFn,
1108
- abort: abortController == null ? void 0 : abortController.abort.bind(abortController),
1109
- onSuccess: data => {
1110
- var _this$cache$config$on2, _this$cache$config2;
1111
-
1112
- if (typeof data === 'undefined') {
1113
- onError(new Error('Query data cannot be undefined'));
1114
- return;
1115
- }
1116
-
1117
- this.setData(data); // Notify cache callback
1118
-
1119
- (_this$cache$config$on2 = (_this$cache$config2 = this.cache.config).onSuccess) == null ? void 0 : _this$cache$config$on2.call(_this$cache$config2, data, this);
1120
-
1121
- if (!this.isFetchingOptimistic) {
1122
- // Schedule query gc after fetching
1123
- this.scheduleGc();
1124
- }
1125
-
1126
- this.isFetchingOptimistic = false;
1127
- },
1128
- onError,
1129
- onFail: () => {
1130
- this.dispatch({
1131
- type: 'failed'
1132
- });
1133
- },
1134
- onPause: () => {
1135
- this.dispatch({
1136
- type: 'pause'
1137
- });
1138
- },
1139
- onContinue: () => {
1140
- this.dispatch({
1141
- type: 'continue'
1142
- });
1143
- },
1144
- retry: context.options.retry,
1145
- retryDelay: context.options.retryDelay,
1146
- networkMode: context.options.networkMode
1147
- });
1148
- this.promise = this.retryer.promise;
1149
- return this.promise;
1150
- }
1151
-
1152
- dispatch(action) {
1153
- const reducer = state => {
1154
- var _action$meta, _action$dataUpdatedAt;
1155
-
1156
- switch (action.type) {
1157
- case 'failed':
1158
- return { ...state,
1159
- fetchFailureCount: state.fetchFailureCount + 1
1160
- };
1161
-
1162
- case 'pause':
1163
- return { ...state,
1164
- fetchStatus: 'paused'
1165
- };
1166
-
1167
- case 'continue':
1168
- return { ...state,
1169
- fetchStatus: 'fetching'
1170
- };
1171
-
1172
- case 'fetch':
1173
- return { ...state,
1174
- fetchFailureCount: 0,
1175
- fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
1176
- fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
1177
- ...(!state.dataUpdatedAt && {
1178
- error: null,
1179
- status: 'loading'
1180
- })
1181
- };
1182
-
1183
- case 'success':
1184
- return { ...state,
1185
- data: action.data,
1186
- dataUpdateCount: state.dataUpdateCount + 1,
1187
- dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
1188
- error: null,
1189
- isInvalidated: false,
1190
- status: 'success',
1191
- ...(!action.manual && {
1192
- fetchStatus: 'idle',
1193
- fetchFailureCount: 0
1194
- })
1195
- };
1196
-
1197
- case 'error':
1198
- const error = action.error;
1199
-
1200
- if (isCancelledError(error) && error.revert && this.revertState) {
1201
- return { ...this.revertState
1202
- };
1203
- }
1204
-
1205
- return { ...state,
1206
- error: error,
1207
- errorUpdateCount: state.errorUpdateCount + 1,
1208
- errorUpdatedAt: Date.now(),
1209
- fetchFailureCount: state.fetchFailureCount + 1,
1210
- fetchStatus: 'idle',
1211
- status: 'error'
1212
- };
1213
-
1214
- case 'invalidate':
1215
- return { ...state,
1216
- isInvalidated: true
1217
- };
1218
-
1219
- case 'setState':
1220
- return { ...state,
1221
- ...action.state
1222
- };
1223
- }
1224
- };
1225
-
1226
- this.state = reducer(this.state);
1227
- notifyManager.batch(() => {
1228
- this.observers.forEach(observer => {
1229
- observer.onQueryUpdate(action);
1230
- });
1231
- this.cache.notify({
1232
- query: this,
1233
- type: 'updated',
1234
- action
1235
- });
1236
- });
1237
- }
1238
-
1239
- }
1240
-
1241
- function getDefaultState$1(options) {
1242
- const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1243
- const hasInitialData = typeof options.initialData !== 'undefined';
1244
- const initialDataUpdatedAt = hasInitialData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1245
- const hasData = typeof data !== 'undefined';
1246
- return {
1247
- data,
1248
- dataUpdateCount: 0,
1249
- dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
1250
- error: null,
1251
- errorUpdateCount: 0,
1252
- errorUpdatedAt: 0,
1253
- fetchFailureCount: 0,
1254
- fetchMeta: null,
1255
- isInvalidated: false,
1256
- status: hasData ? 'success' : 'loading',
1257
- fetchStatus: 'idle'
1258
- };
1259
- }
1260
-
1261
- // CLASS
1262
- class QueryCache extends Subscribable {
1263
- constructor(config) {
1264
- super();
1265
- this.config = config || {};
1266
- this.queries = [];
1267
- this.queriesMap = {};
1268
- }
1269
-
1270
- build(client, options, state) {
1271
- var _options$queryHash;
1272
-
1273
- const queryKey = options.queryKey;
1274
- const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
1275
- let query = this.get(queryHash);
1276
-
1277
- if (!query) {
1278
- query = new Query({
1279
- cache: this,
1280
- logger: client.getLogger(),
1281
- queryKey,
1282
- queryHash,
1283
- options: client.defaultQueryOptions(options),
1284
- state,
1285
- defaultOptions: client.getQueryDefaults(queryKey),
1286
- meta: options.meta
1287
- });
1288
- this.add(query);
1289
- }
1290
-
1291
- return query;
1292
- }
1293
-
1294
- add(query) {
1295
- if (!this.queriesMap[query.queryHash]) {
1296
- this.queriesMap[query.queryHash] = query;
1297
- this.queries.push(query);
1298
- this.notify({
1299
- type: 'added',
1300
- query
1301
- });
1302
- }
1303
- }
1304
-
1305
- remove(query) {
1306
- const queryInMap = this.queriesMap[query.queryHash];
1307
-
1308
- if (queryInMap) {
1309
- query.destroy();
1310
- this.queries = this.queries.filter(x => x !== query);
1311
-
1312
- if (queryInMap === query) {
1313
- delete this.queriesMap[query.queryHash];
1314
- }
1315
-
1316
- this.notify({
1317
- type: 'removed',
1318
- query
1319
- });
1320
- }
1321
- }
1322
-
1323
- clear() {
1324
- notifyManager.batch(() => {
1325
- this.queries.forEach(query => {
1326
- this.remove(query);
1327
- });
1328
- });
1329
- }
1330
-
1331
- get(queryHash) {
1332
- return this.queriesMap[queryHash];
1333
- }
1334
-
1335
- getAll() {
1336
- return this.queries;
1337
- }
1338
-
1339
- find(arg1, arg2) {
1340
- const [filters] = parseFilterArgs(arg1, arg2);
1341
-
1342
- if (typeof filters.exact === 'undefined') {
1343
- filters.exact = true;
1344
- }
1345
-
1346
- return this.queries.find(query => matchQuery(filters, query));
1347
- }
1348
-
1349
- findAll(arg1, arg2) {
1350
- const [filters] = parseFilterArgs(arg1, arg2);
1351
- return Object.keys(filters).length > 0 ? this.queries.filter(query => matchQuery(filters, query)) : this.queries;
1352
- }
1353
-
1354
- notify(event) {
1355
- notifyManager.batch(() => {
1356
- this.listeners.forEach(listener => {
1357
- listener(event);
1358
- });
1359
- });
1360
- }
1361
-
1362
- onFocus() {
1363
- notifyManager.batch(() => {
1364
- this.queries.forEach(query => {
1365
- query.onFocus();
1366
- });
1367
- });
1368
- }
1369
-
1370
- onOnline() {
1371
- notifyManager.batch(() => {
1372
- this.queries.forEach(query => {
1373
- query.onOnline();
1374
- });
1375
- });
1376
- }
1377
-
1378
- }
1379
-
1380
- // CLASS
1381
- class Mutation extends Removable {
1382
- constructor(config) {
1383
- super();
1384
- this.options = { ...config.defaultOptions,
1385
- ...config.options
1386
- };
1387
- this.mutationId = config.mutationId;
1388
- this.mutationCache = config.mutationCache;
1389
- this.logger = config.logger || defaultLogger;
1390
- this.observers = [];
1391
- this.state = config.state || getDefaultState();
1392
- this.meta = config.meta;
1393
- this.updateCacheTime(this.options.cacheTime);
1394
- this.scheduleGc();
1395
- }
1396
-
1397
- setState(state) {
1398
- this.dispatch({
1399
- type: 'setState',
1400
- state
1401
- });
1402
- }
1403
-
1404
- addObserver(observer) {
1405
- if (this.observers.indexOf(observer) === -1) {
1406
- this.observers.push(observer); // Stop the mutation from being garbage collected
1407
-
1408
- this.clearGcTimeout();
1409
- this.mutationCache.notify({
1410
- type: 'observerAdded',
1411
- mutation: this,
1412
- observer
1413
- });
1414
- }
1415
- }
1416
-
1417
- removeObserver(observer) {
1418
- this.observers = this.observers.filter(x => x !== observer);
1419
- this.scheduleGc();
1420
- this.mutationCache.notify({
1421
- type: 'observerRemoved',
1422
- mutation: this,
1423
- observer
1424
- });
1425
- }
1426
-
1427
- optionalRemove() {
1428
- if (!this.observers.length) {
1429
- if (this.state.status === 'loading') {
1430
- this.scheduleGc();
1431
- } else {
1432
- this.mutationCache.remove(this);
1433
- }
1434
- }
1435
- }
1436
-
1437
- continue() {
1438
- if (this.retryer) {
1439
- this.retryer.continue();
1440
- return this.retryer.promise;
1441
- }
1442
-
1443
- return this.execute();
1444
- }
1445
-
1446
- async execute() {
1447
- const executeMutation = () => {
1448
- var _this$options$retry;
1449
-
1450
- this.retryer = createRetryer({
1451
- fn: () => {
1452
- if (!this.options.mutationFn) {
1453
- return Promise.reject('No mutationFn found');
1454
- }
1455
-
1456
- return this.options.mutationFn(this.state.variables);
1457
- },
1458
- onFail: () => {
1459
- this.dispatch({
1460
- type: 'failed'
1461
- });
1462
- },
1463
- onPause: () => {
1464
- this.dispatch({
1465
- type: 'pause'
1466
- });
1467
- },
1468
- onContinue: () => {
1469
- this.dispatch({
1470
- type: 'continue'
1471
- });
1472
- },
1473
- retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
1474
- retryDelay: this.options.retryDelay,
1475
- networkMode: this.options.networkMode
1476
- });
1477
- return this.retryer.promise;
1478
- };
1479
-
1480
- const restored = this.state.status === 'loading';
1481
-
1482
- try {
1483
- var _this$mutationCache$c3, _this$mutationCache$c4, _this$options$onSucce, _this$options2, _this$options$onSettl, _this$options3;
1484
-
1485
- if (!restored) {
1486
- var _this$mutationCache$c, _this$mutationCache$c2, _this$options$onMutat, _this$options;
1487
-
1488
- this.dispatch({
1489
- type: 'loading',
1490
- variables: this.options.variables
1491
- }); // Notify cache callback
1492
-
1493
- (_this$mutationCache$c = (_this$mutationCache$c2 = this.mutationCache.config).onMutate) == null ? void 0 : _this$mutationCache$c.call(_this$mutationCache$c2, this.state.variables, this);
1494
- const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, this.state.variables));
1495
-
1496
- if (context !== this.state.context) {
1497
- this.dispatch({
1498
- type: 'loading',
1499
- context,
1500
- variables: this.state.variables
1501
- });
1502
- }
1503
- }
1504
-
1505
- const data = await executeMutation(); // Notify cache callback
1506
-
1507
- (_this$mutationCache$c3 = (_this$mutationCache$c4 = this.mutationCache.config).onSuccess) == null ? void 0 : _this$mutationCache$c3.call(_this$mutationCache$c4, data, this.state.variables, this.state.context, this);
1508
- await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options2, data, this.state.variables, this.state.context));
1509
- await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options3, data, null, this.state.variables, this.state.context));
1510
- this.dispatch({
1511
- type: 'success',
1512
- data
1513
- });
1514
- return data;
1515
- } catch (error) {
1516
- try {
1517
- var _this$mutationCache$c5, _this$mutationCache$c6, _this$options$onError, _this$options4, _this$options$onSettl2, _this$options5;
1518
-
1519
- // Notify cache callback
1520
- (_this$mutationCache$c5 = (_this$mutationCache$c6 = this.mutationCache.config).onError) == null ? void 0 : _this$mutationCache$c5.call(_this$mutationCache$c6, error, this.state.variables, this.state.context, this);
1521
-
1522
- if (process.env.NODE_ENV !== 'production') {
1523
- this.logger.error(error);
1524
- }
1525
-
1526
- await ((_this$options$onError = (_this$options4 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options4, error, this.state.variables, this.state.context));
1527
- await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options5, undefined, error, this.state.variables, this.state.context));
1528
- throw error;
1529
- } finally {
1530
- this.dispatch({
1531
- type: 'error',
1532
- error: error
1533
- });
1534
- }
1535
- }
1536
- }
1537
-
1538
- dispatch(action) {
1539
- const reducer = state => {
1540
- switch (action.type) {
1541
- case 'failed':
1542
- return { ...state,
1543
- failureCount: state.failureCount + 1
1544
- };
1545
-
1546
- case 'pause':
1547
- return { ...state,
1548
- isPaused: true
1549
- };
1550
-
1551
- case 'continue':
1552
- return { ...state,
1553
- isPaused: false
1554
- };
1555
-
1556
- case 'loading':
1557
- return { ...state,
1558
- context: action.context,
1559
- data: undefined,
1560
- error: null,
1561
- isPaused: !canFetch(this.options.networkMode),
1562
- status: 'loading',
1563
- variables: action.variables
1564
- };
1565
-
1566
- case 'success':
1567
- return { ...state,
1568
- data: action.data,
1569
- error: null,
1570
- status: 'success',
1571
- isPaused: false
1572
- };
1573
-
1574
- case 'error':
1575
- return { ...state,
1576
- data: undefined,
1577
- error: action.error,
1578
- failureCount: state.failureCount + 1,
1579
- isPaused: false,
1580
- status: 'error'
1581
- };
1582
-
1583
- case 'setState':
1584
- return { ...state,
1585
- ...action.state
1586
- };
1587
- }
1588
- };
1589
-
1590
- this.state = reducer(this.state);
1591
- notifyManager.batch(() => {
1592
- this.observers.forEach(observer => {
1593
- observer.onMutationUpdate(action);
1594
- });
1595
- this.mutationCache.notify({
1596
- mutation: this,
1597
- type: 'updated',
1598
- action
1599
- });
1600
- });
1601
- }
1602
-
1603
- }
1604
- function getDefaultState() {
1605
- return {
1606
- context: undefined,
1607
- data: undefined,
1608
- error: null,
1609
- failureCount: 0,
1610
- isPaused: false,
1611
- status: 'idle',
1612
- variables: undefined
1613
- };
1614
- }
1615
-
1616
- // CLASS
1617
- class MutationCache extends Subscribable {
1618
- constructor(config) {
1619
- super();
1620
- this.config = config || {};
1621
- this.mutations = [];
1622
- this.mutationId = 0;
1623
- }
1624
-
1625
- build(client, options, state) {
1626
- const mutation = new Mutation({
1627
- mutationCache: this,
1628
- logger: client.getLogger(),
1629
- mutationId: ++this.mutationId,
1630
- options: client.defaultMutationOptions(options),
1631
- state,
1632
- defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined,
1633
- meta: options.meta
1634
- });
1635
- this.add(mutation);
1636
- return mutation;
1637
- }
1638
-
1639
- add(mutation) {
1640
- this.mutations.push(mutation);
1641
- this.notify({
1642
- type: 'added',
1643
- mutation
1644
- });
1645
- }
1646
-
1647
- remove(mutation) {
1648
- this.mutations = this.mutations.filter(x => x !== mutation);
1649
- this.notify({
1650
- type: 'removed',
1651
- mutation
1652
- });
1653
- }
1654
-
1655
- clear() {
1656
- notifyManager.batch(() => {
1657
- this.mutations.forEach(mutation => {
1658
- this.remove(mutation);
1659
- });
1660
- });
1661
- }
1662
-
1663
- getAll() {
1664
- return this.mutations;
1665
- }
1666
-
1667
- find(filters) {
1668
- if (typeof filters.exact === 'undefined') {
1669
- filters.exact = true;
1670
- }
1671
-
1672
- return this.mutations.find(mutation => matchMutation(filters, mutation));
1673
- }
1674
-
1675
- findAll(filters) {
1676
- return this.mutations.filter(mutation => matchMutation(filters, mutation));
1677
- }
1678
-
1679
- notify(event) {
1680
- notifyManager.batch(() => {
1681
- this.listeners.forEach(listener => {
1682
- listener(event);
1683
- });
1684
- });
1685
- }
1686
-
1687
- resumePausedMutations() {
1688
- const pausedMutations = this.mutations.filter(x => x.state.isPaused);
1689
- return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop)), Promise.resolve()));
1690
- }
1691
-
1692
- }
1693
-
1694
- function infiniteQueryBehavior() {
1695
- return {
1696
- onFetch: context => {
1697
- context.fetchFn = () => {
1698
- var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
1699
-
1700
- const refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
1701
- const fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
1702
- const pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
1703
- const isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
1704
- const isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
1705
- const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
1706
- const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
1707
- let newPageParams = oldPageParams;
1708
- let cancelled = false;
1709
-
1710
- const addSignalProperty = object => {
1711
- Object.defineProperty(object, 'signal', {
1712
- enumerable: true,
1713
- get: () => {
1714
- var _context$signal;
1715
-
1716
- if ((_context$signal = context.signal) != null && _context$signal.aborted) {
1717
- cancelled = true;
1718
- } else {
1719
- var _context$signal2;
1720
-
1721
- (_context$signal2 = context.signal) == null ? void 0 : _context$signal2.addEventListener('abort', () => {
1722
- cancelled = true;
1723
- });
1724
- }
1725
-
1726
- return context.signal;
1727
- }
1728
- });
1729
- }; // Get query function
1730
-
1731
-
1732
- const queryFn = context.options.queryFn || (() => Promise.reject('Missing queryFn'));
1733
-
1734
- const buildNewPages = (pages, param, page, previous) => {
1735
- newPageParams = previous ? [param, ...newPageParams] : [...newPageParams, param];
1736
- return previous ? [page, ...pages] : [...pages, page];
1737
- }; // Create function to fetch a page
1738
-
1739
-
1740
- const fetchPage = (pages, manual, param, previous) => {
1741
- if (cancelled) {
1742
- return Promise.reject('Cancelled');
1743
- }
1744
-
1745
- if (typeof param === 'undefined' && !manual && pages.length) {
1746
- return Promise.resolve(pages);
1747
- }
1748
-
1749
- const queryFnContext = {
1750
- queryKey: context.queryKey,
1751
- pageParam: param,
1752
- meta: context.meta
1753
- };
1754
- addSignalProperty(queryFnContext);
1755
- const queryFnResult = queryFn(queryFnContext);
1756
- const promise = Promise.resolve(queryFnResult).then(page => buildNewPages(pages, param, page, previous));
1757
- return promise;
1758
- };
1759
-
1760
- let promise; // Fetch first page?
1761
-
1762
- if (!oldPages.length) {
1763
- promise = fetchPage([]);
1764
- } // Fetch next page?
1765
- else if (isFetchingNextPage) {
1766
- const manual = typeof pageParam !== 'undefined';
1767
- const param = manual ? pageParam : getNextPageParam(context.options, oldPages);
1768
- promise = fetchPage(oldPages, manual, param);
1769
- } // Fetch previous page?
1770
- else if (isFetchingPreviousPage) {
1771
- const manual = typeof pageParam !== 'undefined';
1772
- const param = manual ? pageParam : getPreviousPageParam(context.options, oldPages);
1773
- promise = fetchPage(oldPages, manual, param, true);
1774
- } // Refetch pages
1775
- else {
1776
- newPageParams = [];
1777
- const manual = typeof context.options.getNextPageParam === 'undefined';
1778
- const shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
1779
-
1780
- promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
1781
-
1782
- for (let i = 1; i < oldPages.length; i++) {
1783
- promise = promise.then(pages => {
1784
- const shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
1785
-
1786
- if (shouldFetchNextPage) {
1787
- const param = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
1788
- return fetchPage(pages, manual, param);
1789
- }
1790
-
1791
- return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
1792
- });
1793
- }
1794
- }
1795
-
1796
- const finalPromise = promise.then(pages => ({
1797
- pages,
1798
- pageParams: newPageParams
1799
- }));
1800
- return finalPromise;
1801
- };
1802
- }
1803
- };
1804
- }
1805
- function getNextPageParam(options, pages) {
1806
- return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
1807
- }
1808
- function getPreviousPageParam(options, pages) {
1809
- return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
1810
- }
1811
- /**
1812
- * Checks if there is a next page.
1813
- * Returns `undefined` if it cannot be determined.
1814
- */
1815
-
1816
- function hasNextPage(options, pages) {
1817
- if (options.getNextPageParam && Array.isArray(pages)) {
1818
- const nextPageParam = getNextPageParam(options, pages);
1819
- return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
1820
- }
1821
- }
1822
- /**
1823
- * Checks if there is a previous page.
1824
- * Returns `undefined` if it cannot be determined.
1825
- */
1826
-
1827
- function hasPreviousPage(options, pages) {
1828
- if (options.getPreviousPageParam && Array.isArray(pages)) {
1829
- const previousPageParam = getPreviousPageParam(options, pages);
1830
- return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
1831
- }
1832
- }
1833
-
1834
- // CLASS
1835
- class QueryClient {
1836
- constructor(config = {}) {
1837
- this.queryCache = config.queryCache || new QueryCache();
1838
- this.mutationCache = config.mutationCache || new MutationCache();
1839
- this.logger = config.logger || defaultLogger;
1840
- this.defaultOptions = config.defaultOptions || {};
1841
- this.queryDefaults = [];
1842
- this.mutationDefaults = [];
1843
- }
1844
-
1845
- mount() {
1846
- this.unsubscribeFocus = focusManager.subscribe(() => {
1847
- if (focusManager.isFocused()) {
1848
- this.resumePausedMutations();
1849
- this.queryCache.onFocus();
1850
- }
1851
- });
1852
- this.unsubscribeOnline = onlineManager.subscribe(() => {
1853
- if (onlineManager.isOnline()) {
1854
- this.resumePausedMutations();
1855
- this.queryCache.onOnline();
1856
- }
1857
- });
1858
- }
1859
-
1860
- unmount() {
1861
- var _this$unsubscribeFocu, _this$unsubscribeOnli;
1862
-
1863
- (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
1864
- (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
1865
- }
1866
-
1867
- isFetching(arg1, arg2) {
1868
- const [filters] = parseFilterArgs(arg1, arg2);
1869
- filters.fetchStatus = 'fetching';
1870
- return this.queryCache.findAll(filters).length;
1871
- }
1872
-
1873
- isMutating(filters) {
1874
- return this.mutationCache.findAll({ ...filters,
1875
- fetching: true
1876
- }).length;
1877
- }
1878
-
1879
- getQueryData(queryKey, filters) {
1880
- var _this$queryCache$find;
1881
-
1882
- return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
1883
- }
1884
-
1885
- getQueriesData(queryKeyOrFilters) {
1886
- return this.getQueryCache().findAll(queryKeyOrFilters).map(({
1887
- queryKey,
1888
- state
1889
- }) => {
1890
- const data = state.data;
1891
- return [queryKey, data];
1892
- });
1893
- }
1894
-
1895
- setQueryData(queryKey, updater, options) {
1896
- const query = this.queryCache.find(queryKey);
1897
- const prevData = query == null ? void 0 : query.state.data;
1898
- const data = functionalUpdate(updater, prevData);
1899
-
1900
- if (typeof data === 'undefined') {
1901
- return undefined;
1902
- }
1903
-
1904
- const parsedOptions = parseQueryArgs(queryKey);
1905
- const defaultedOptions = this.defaultQueryOptions(parsedOptions);
1906
- return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
1907
- manual: true
1908
- });
1909
- }
1910
-
1911
- setQueriesData(queryKeyOrFilters, updater, options) {
1912
- return notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
1913
- queryKey
1914
- }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
1915
- }
1916
-
1917
- getQueryState(queryKey, filters) {
1918
- var _this$queryCache$find2;
1919
-
1920
- return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
1921
- }
1922
-
1923
- removeQueries(arg1, arg2) {
1924
- const [filters] = parseFilterArgs(arg1, arg2);
1925
- const queryCache = this.queryCache;
1926
- notifyManager.batch(() => {
1927
- queryCache.findAll(filters).forEach(query => {
1928
- queryCache.remove(query);
1929
- });
1930
- });
1931
- }
1932
-
1933
- resetQueries(arg1, arg2, arg3) {
1934
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
1935
- const queryCache = this.queryCache;
1936
- const refetchFilters = {
1937
- type: 'active',
1938
- ...filters
1939
- };
1940
- return notifyManager.batch(() => {
1941
- queryCache.findAll(filters).forEach(query => {
1942
- query.reset();
1943
- });
1944
- return this.refetchQueries(refetchFilters, options);
1945
- });
1946
- }
1947
-
1948
- cancelQueries(arg1, arg2, arg3) {
1949
- const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3);
1950
-
1951
- if (typeof cancelOptions.revert === 'undefined') {
1952
- cancelOptions.revert = true;
1953
- }
1954
-
1955
- const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1956
- return Promise.all(promises).then(noop).catch(noop);
1957
- }
1958
-
1959
- invalidateQueries(arg1, arg2, arg3) {
1960
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
1961
- return notifyManager.batch(() => {
1962
- var _ref, _filters$refetchType;
1963
-
1964
- this.queryCache.findAll(filters).forEach(query => {
1965
- query.invalidate();
1966
- });
1967
-
1968
- if (filters.refetchType === 'none') {
1969
- return Promise.resolve();
1970
- }
1971
-
1972
- const refetchFilters = { ...filters,
1973
- type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
1974
- };
1975
- return this.refetchQueries(refetchFilters, options);
1976
- });
1977
- }
1978
-
1979
- refetchQueries(arg1, arg2, arg3) {
1980
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
1981
- const promises = notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
1982
- var _options$cancelRefetc;
1983
-
1984
- return query.fetch(undefined, { ...options,
1985
- cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
1986
- meta: {
1987
- refetchPage: filters.refetchPage
1988
- }
1989
- });
1990
- }));
1991
- let promise = Promise.all(promises).then(noop);
1992
-
1993
- if (!(options != null && options.throwOnError)) {
1994
- promise = promise.catch(noop);
1995
- }
1996
-
1997
- return promise;
1998
- }
1999
-
2000
- fetchQuery(arg1, arg2, arg3) {
2001
- const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2002
- const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
2003
-
2004
- if (typeof defaultedOptions.retry === 'undefined') {
2005
- defaultedOptions.retry = false;
2006
- }
2007
-
2008
- const query = this.queryCache.build(this, defaultedOptions);
2009
- return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2010
- }
2011
-
2012
- prefetchQuery(arg1, arg2, arg3) {
2013
- return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);
2014
- }
2015
-
2016
- fetchInfiniteQuery(arg1, arg2, arg3) {
2017
- const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2018
- parsedOptions.behavior = infiniteQueryBehavior();
2019
- return this.fetchQuery(parsedOptions);
2020
- }
2021
-
2022
- prefetchInfiniteQuery(arg1, arg2, arg3) {
2023
- return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);
2024
- }
2025
-
2026
- resumePausedMutations() {
2027
- return this.mutationCache.resumePausedMutations();
2028
- }
2029
-
2030
- getQueryCache() {
2031
- return this.queryCache;
2032
- }
2033
-
2034
- getMutationCache() {
2035
- return this.mutationCache;
2036
- }
2037
-
2038
- getLogger() {
2039
- return this.logger;
2040
- }
2041
-
2042
- getDefaultOptions() {
2043
- return this.defaultOptions;
2044
- }
2045
-
2046
- setDefaultOptions(options) {
2047
- this.defaultOptions = options;
2048
- }
2049
-
2050
- setQueryDefaults(queryKey, options) {
2051
- const result = this.queryDefaults.find(x => hashQueryKey(queryKey) === hashQueryKey(x.queryKey));
2052
-
2053
- if (result) {
2054
- result.defaultOptions = options;
2055
- } else {
2056
- this.queryDefaults.push({
2057
- queryKey,
2058
- defaultOptions: options
2059
- });
2060
- }
2061
- }
2062
-
2063
- getQueryDefaults(queryKey) {
2064
- if (!queryKey) {
2065
- return undefined;
2066
- } // Get the first matching defaults
2067
-
2068
-
2069
- const firstMatchingDefaults = this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode
2070
-
2071
- if (process.env.NODE_ENV !== 'production') {
2072
- // Retrieve all matching defaults for the given key
2073
- const matchingDefaults = this.queryDefaults.filter(x => partialMatchKey(queryKey, x.queryKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
2074
-
2075
- if (matchingDefaults.length > 1) {
2076
- this.logger.error("[QueryClient] Several query defaults match with key '" + JSON.stringify(queryKey) + "'. The first matching query defaults are used. Please check how query defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetquerydefaults.");
2077
- }
2078
- }
2079
-
2080
- return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2081
- }
2082
-
2083
- setMutationDefaults(mutationKey, options) {
2084
- const result = this.mutationDefaults.find(x => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey));
2085
-
2086
- if (result) {
2087
- result.defaultOptions = options;
2088
- } else {
2089
- this.mutationDefaults.push({
2090
- mutationKey,
2091
- defaultOptions: options
2092
- });
2093
- }
2094
- }
2095
-
2096
- getMutationDefaults(mutationKey) {
2097
- if (!mutationKey) {
2098
- return undefined;
2099
- } // Get the first matching defaults
2100
-
2101
-
2102
- const firstMatchingDefaults = this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
2103
-
2104
- if (process.env.NODE_ENV !== 'production') {
2105
- // Retrieve all matching defaults for the given key
2106
- const matchingDefaults = this.mutationDefaults.filter(x => partialMatchKey(mutationKey, x.mutationKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
2107
-
2108
- if (matchingDefaults.length > 1) {
2109
- this.logger.error("[QueryClient] Several mutation defaults match with key '" + JSON.stringify(mutationKey) + "'. The first matching mutation defaults are used. Please check how mutation defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetmutationdefaults.");
2110
- }
2111
- }
2112
-
2113
- return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2114
- }
2115
-
2116
- defaultQueryOptions(options) {
2117
- if (options != null && options._defaulted) {
2118
- return options;
2119
- }
2120
-
2121
- const defaultedOptions = { ...this.defaultOptions.queries,
2122
- ...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
2123
- ...options,
2124
- _defaulted: true
2125
- };
2126
-
2127
- if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
2128
- defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
2129
- } // dependent default values
2130
-
2131
-
2132
- if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
2133
- defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
2134
- }
2135
-
2136
- if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
2137
- defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
2138
- }
2139
-
2140
- return defaultedOptions;
2141
- }
2142
-
2143
- defaultMutationOptions(options) {
2144
- if (options != null && options._defaulted) {
2145
- return options;
2146
- }
2147
-
2148
- return { ...this.defaultOptions.mutations,
2149
- ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
2150
- ...options,
2151
- _defaulted: true
2152
- };
2153
- }
2154
-
2155
- clear() {
2156
- this.queryCache.clear();
2157
- this.mutationCache.clear();
2158
- }
2159
-
2160
- }
2161
-
2162
- class QueryObserver extends Subscribable {
2163
- constructor(client, options) {
2164
- super();
2165
- this.client = client;
2166
- this.options = options;
2167
- this.trackedProps = new Set();
2168
- this.selectError = null;
2169
- this.bindMethods();
2170
- this.setOptions(options);
2171
- }
2172
-
2173
- bindMethods() {
2174
- this.remove = this.remove.bind(this);
2175
- this.refetch = this.refetch.bind(this);
2176
- }
2177
-
2178
- onSubscribe() {
2179
- if (this.listeners.length === 1) {
2180
- this.currentQuery.addObserver(this);
2181
-
2182
- if (shouldFetchOnMount(this.currentQuery, this.options)) {
2183
- this.executeFetch();
2184
- }
2185
-
2186
- this.updateTimers();
2187
- }
2188
- }
2189
-
2190
- onUnsubscribe() {
2191
- if (!this.listeners.length) {
2192
- this.destroy();
2193
- }
2194
- }
2195
-
2196
- shouldFetchOnReconnect() {
2197
- return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
2198
- }
2199
-
2200
- shouldFetchOnWindowFocus() {
2201
- return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
2202
- }
2203
-
2204
- destroy() {
2205
- this.listeners = [];
2206
- this.clearStaleTimeout();
2207
- this.clearRefetchInterval();
2208
- this.currentQuery.removeObserver(this);
2209
- }
2210
-
2211
- setOptions(options, notifyOptions) {
2212
- const prevOptions = this.options;
2213
- const prevQuery = this.currentQuery;
2214
- this.options = this.client.defaultQueryOptions(options);
2215
-
2216
- if (!shallowEqualObjects(prevOptions, this.options)) {
2217
- this.client.getQueryCache().notify({
2218
- type: 'observerOptionsUpdated',
2219
- query: this.currentQuery,
2220
- observer: this
2221
- });
2222
- }
2223
-
2224
- if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
2225
- throw new Error('Expected enabled to be a boolean');
2226
- } // Keep previous query key if the user does not supply one
2227
-
2228
-
2229
- if (!this.options.queryKey) {
2230
- this.options.queryKey = prevOptions.queryKey;
2231
- }
2232
-
2233
- this.updateQuery();
2234
- const mounted = this.hasListeners(); // Fetch if there are subscribers
2235
-
2236
- if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
2237
- this.executeFetch();
2238
- } // Update result
2239
-
2240
-
2241
- this.updateResult(notifyOptions); // Update stale interval if needed
2242
-
2243
- if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
2244
- this.updateStaleTimeout();
2245
- }
2246
-
2247
- const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
2248
-
2249
- if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
2250
- this.updateRefetchInterval(nextRefetchInterval);
2251
- }
2252
- }
2253
-
2254
- getOptimisticResult(options) {
2255
- const query = this.client.getQueryCache().build(this.client, options);
2256
- return this.createResult(query, options);
2257
- }
2258
-
2259
- getCurrentResult() {
2260
- return this.currentResult;
2261
- }
2262
-
2263
- trackResult(result) {
2264
- const trackedResult = {};
2265
- Object.keys(result).forEach(key => {
2266
- Object.defineProperty(trackedResult, key, {
2267
- configurable: false,
2268
- enumerable: true,
2269
- get: () => {
2270
- this.trackedProps.add(key);
2271
- return result[key];
2272
- }
2273
- });
2274
- });
2275
- return trackedResult;
2276
- }
2277
-
2278
- getCurrentQuery() {
2279
- return this.currentQuery;
2280
- }
2281
-
2282
- remove() {
2283
- this.client.getQueryCache().remove(this.currentQuery);
2284
- }
2285
-
2286
- refetch({
2287
- refetchPage,
2288
- ...options
2289
- } = {}) {
2290
- return this.fetch({ ...options,
2291
- meta: {
2292
- refetchPage
2293
- }
2294
- });
2295
- }
2296
-
2297
- fetchOptimistic(options) {
2298
- const defaultedOptions = this.client.defaultQueryOptions(options);
2299
- const query = this.client.getQueryCache().build(this.client, defaultedOptions);
2300
- query.isFetchingOptimistic = true;
2301
- return query.fetch().then(() => this.createResult(query, defaultedOptions));
2302
- }
2303
-
2304
- fetch(fetchOptions) {
2305
- var _fetchOptions$cancelR;
2306
-
2307
- return this.executeFetch({ ...fetchOptions,
2308
- cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
2309
- }).then(() => {
2310
- this.updateResult();
2311
- return this.currentResult;
2312
- });
2313
- }
2314
-
2315
- executeFetch(fetchOptions) {
2316
- // Make sure we reference the latest query as the current one might have been removed
2317
- this.updateQuery(); // Fetch
2318
-
2319
- let promise = this.currentQuery.fetch(this.options, fetchOptions);
2320
-
2321
- if (!(fetchOptions != null && fetchOptions.throwOnError)) {
2322
- promise = promise.catch(noop);
2323
- }
2324
-
2325
- return promise;
2326
- }
2327
-
2328
- updateStaleTimeout() {
2329
- this.clearStaleTimeout();
2330
-
2331
- if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
2332
- return;
2333
- }
2334
-
2335
- const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
2336
- // To mitigate this issue we always add 1 ms to the timeout.
2337
-
2338
- const timeout = time + 1;
2339
- this.staleTimeoutId = setTimeout(() => {
2340
- if (!this.currentResult.isStale) {
2341
- this.updateResult();
2342
- }
2343
- }, timeout);
2344
- }
2345
-
2346
- computeRefetchInterval() {
2347
- var _this$options$refetch;
2348
-
2349
- return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
2350
- }
2351
-
2352
- updateRefetchInterval(nextInterval) {
2353
- this.clearRefetchInterval();
2354
- this.currentRefetchInterval = nextInterval;
2355
-
2356
- if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
2357
- return;
2358
- }
2359
-
2360
- this.refetchIntervalId = setInterval(() => {
2361
- if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2362
- this.executeFetch();
2363
- }
2364
- }, this.currentRefetchInterval);
2365
- }
2366
-
2367
- updateTimers() {
2368
- this.updateStaleTimeout();
2369
- this.updateRefetchInterval(this.computeRefetchInterval());
2370
- }
2371
-
2372
- clearStaleTimeout() {
2373
- if (this.staleTimeoutId) {
2374
- clearTimeout(this.staleTimeoutId);
2375
- this.staleTimeoutId = undefined;
2376
- }
2377
- }
2378
-
2379
- clearRefetchInterval() {
2380
- if (this.refetchIntervalId) {
2381
- clearInterval(this.refetchIntervalId);
2382
- this.refetchIntervalId = undefined;
2383
- }
2384
- }
2385
-
2386
- createResult(query, options) {
2387
- const prevQuery = this.currentQuery;
2388
- const prevOptions = this.options;
2389
- const prevResult = this.currentResult;
2390
- const prevResultState = this.currentResultState;
2391
- const prevResultOptions = this.currentResultOptions;
2392
- const queryChange = query !== prevQuery;
2393
- const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
2394
- const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
2395
- const {
2396
- state
2397
- } = query;
2398
- let {
2399
- dataUpdatedAt,
2400
- error,
2401
- errorUpdatedAt,
2402
- fetchStatus,
2403
- status
2404
- } = state;
2405
- let isPreviousData = false;
2406
- let isPlaceholderData = false;
2407
- let data; // Optimistically set result in fetching state if needed
2408
-
2409
- if (options._optimisticResults) {
2410
- const mounted = this.hasListeners();
2411
- const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2412
- const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2413
-
2414
- if (fetchOnMount || fetchOptionally) {
2415
- fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2416
-
2417
- if (!dataUpdatedAt) {
2418
- status = 'loading';
2419
- }
2420
- }
2421
-
2422
- if (options._optimisticResults === 'isRestoring') {
2423
- fetchStatus = 'idle';
2424
- }
2425
- } // Keep previous data if needed
2426
-
2427
-
2428
- if (options.keepPreviousData && !state.dataUpdateCount && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
2429
- data = prevQueryResult.data;
2430
- dataUpdatedAt = prevQueryResult.dataUpdatedAt;
2431
- status = prevQueryResult.status;
2432
- isPreviousData = true;
2433
- } // Select data if needed
2434
- else if (options.select && typeof state.data !== 'undefined') {
2435
- // Memoize select result
2436
- if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
2437
- data = this.selectResult;
2438
- } else {
2439
- try {
2440
- this.selectFn = options.select;
2441
- data = options.select(state.data);
2442
- data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
2443
- this.selectResult = data;
2444
- this.selectError = null;
2445
- } catch (selectError) {
2446
- if (process.env.NODE_ENV !== 'production') {
2447
- this.client.getLogger().error(selectError);
2448
- }
2449
-
2450
- this.selectError = selectError;
2451
- }
2452
- }
2453
- } // Use query data
2454
- else {
2455
- data = state.data;
2456
- } // Show placeholder data if needed
2457
-
2458
-
2459
- if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
2460
- let placeholderData; // Memoize placeholder data
2461
-
2462
- if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
2463
- placeholderData = prevResult.data;
2464
- } else {
2465
- placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
2466
-
2467
- if (options.select && typeof placeholderData !== 'undefined') {
2468
- try {
2469
- placeholderData = options.select(placeholderData);
2470
- placeholderData = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
2471
- this.selectError = null;
2472
- } catch (selectError) {
2473
- if (process.env.NODE_ENV !== 'production') {
2474
- this.client.getLogger().error(selectError);
2475
- }
2476
-
2477
- this.selectError = selectError;
2478
- }
2479
- }
2480
- }
2481
-
2482
- if (typeof placeholderData !== 'undefined') {
2483
- status = 'success';
2484
- data = placeholderData;
2485
- isPlaceholderData = true;
2486
- }
2487
- }
2488
-
2489
- if (this.selectError) {
2490
- error = this.selectError;
2491
- data = this.selectResult;
2492
- errorUpdatedAt = Date.now();
2493
- status = 'error';
2494
- }
2495
-
2496
- const isFetching = fetchStatus === 'fetching';
2497
- const result = {
2498
- status,
2499
- fetchStatus,
2500
- isLoading: status === 'loading',
2501
- isSuccess: status === 'success',
2502
- isError: status === 'error',
2503
- data,
2504
- dataUpdatedAt,
2505
- error,
2506
- errorUpdatedAt,
2507
- failureCount: state.fetchFailureCount,
2508
- errorUpdateCount: state.errorUpdateCount,
2509
- isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2510
- isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2511
- isFetching: isFetching,
2512
- isRefetching: isFetching && status !== 'loading',
2513
- isLoadingError: status === 'error' && state.dataUpdatedAt === 0,
2514
- isPaused: fetchStatus === 'paused',
2515
- isPlaceholderData,
2516
- isPreviousData,
2517
- isRefetchError: status === 'error' && state.dataUpdatedAt !== 0,
2518
- isStale: isStale(query, options),
2519
- refetch: this.refetch,
2520
- remove: this.remove
2521
- };
2522
- return result;
2523
- }
2524
-
2525
- updateResult(notifyOptions) {
2526
- const prevResult = this.currentResult;
2527
- const nextResult = this.createResult(this.currentQuery, this.options);
2528
- this.currentResultState = this.currentQuery.state;
2529
- this.currentResultOptions = this.options; // Only notify and update result if something has changed
2530
-
2531
- if (shallowEqualObjects(nextResult, prevResult)) {
2532
- return;
2533
- }
2534
-
2535
- this.currentResult = nextResult; // Determine which callbacks to trigger
2536
-
2537
- const defaultNotifyOptions = {
2538
- cache: true
2539
- };
2540
-
2541
- const shouldNotifyListeners = () => {
2542
- if (!prevResult) {
2543
- return true;
2544
- }
2545
-
2546
- const {
2547
- notifyOnChangeProps
2548
- } = this.options;
2549
-
2550
- if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.trackedProps.size) {
2551
- return true;
2552
- }
2553
-
2554
- const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : this.trackedProps);
2555
-
2556
- if (this.options.useErrorBoundary) {
2557
- includedProps.add('error');
2558
- }
2559
-
2560
- return Object.keys(this.currentResult).some(key => {
2561
- const typedKey = key;
2562
- const changed = this.currentResult[typedKey] !== prevResult[typedKey];
2563
- return changed && includedProps.has(typedKey);
2564
- });
2565
- };
2566
-
2567
- if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
2568
- defaultNotifyOptions.listeners = true;
2569
- }
2570
-
2571
- this.notify({ ...defaultNotifyOptions,
2572
- ...notifyOptions
2573
- });
2574
- }
2575
-
2576
- updateQuery() {
2577
- const query = this.client.getQueryCache().build(this.client, this.options);
2578
-
2579
- if (query === this.currentQuery) {
2580
- return;
2581
- }
2582
-
2583
- const prevQuery = this.currentQuery;
2584
- this.currentQuery = query;
2585
- this.currentQueryInitialState = query.state;
2586
- this.previousQueryResult = this.currentResult;
2587
-
2588
- if (this.hasListeners()) {
2589
- prevQuery == null ? void 0 : prevQuery.removeObserver(this);
2590
- query.addObserver(this);
2591
- }
2592
- }
2593
-
2594
- onQueryUpdate(action) {
2595
- const notifyOptions = {};
2596
-
2597
- if (action.type === 'success') {
2598
- notifyOptions.onSuccess = !action.manual;
2599
- } else if (action.type === 'error' && !isCancelledError(action.error)) {
2600
- notifyOptions.onError = true;
2601
- }
2602
-
2603
- this.updateResult(notifyOptions);
2604
-
2605
- if (this.hasListeners()) {
2606
- this.updateTimers();
2607
- }
2608
- }
2609
-
2610
- notify(notifyOptions) {
2611
- notifyManager.batch(() => {
2612
- // First trigger the configuration callbacks
2613
- if (notifyOptions.onSuccess) {
2614
- var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
2615
-
2616
- (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
2617
- (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
2618
- } else if (notifyOptions.onError) {
2619
- var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
2620
-
2621
- (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
2622
- (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
2623
- } // Then trigger the listeners
2624
-
2625
-
2626
- if (notifyOptions.listeners) {
2627
- this.listeners.forEach(listener => {
2628
- listener(this.currentResult);
2629
- });
2630
- } // Then the cache listeners
2631
-
2632
-
2633
- if (notifyOptions.cache) {
2634
- this.client.getQueryCache().notify({
2635
- query: this.currentQuery,
2636
- type: 'observerResultsUpdated'
2637
- });
2638
- }
2639
- });
2640
- }
2641
-
2642
- }
2643
-
2644
- function shouldLoadOnMount(query, options) {
2645
- return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2646
- }
2647
-
2648
- function shouldFetchOnMount(query, options) {
2649
- return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2650
- }
2651
-
2652
- function shouldFetchOn(query, options, field) {
2653
- if (options.enabled !== false) {
2654
- const value = typeof field === 'function' ? field(query) : field;
2655
- return value === 'always' || value !== false && isStale(query, options);
2656
- }
2657
-
2658
- return false;
2659
- }
2660
-
2661
- function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2662
- return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2663
- }
2664
-
2665
- function isStale(query, options) {
2666
- return query.isStaleByTime(options.staleTime);
2667
- }
2668
-
2669
- class QueriesObserver extends Subscribable {
2670
- constructor(client, queries) {
2671
- super();
2672
- this.client = client;
2673
- this.queries = [];
2674
- this.result = [];
2675
- this.observers = [];
2676
- this.observersMap = {};
2677
-
2678
- if (queries) {
2679
- this.setQueries(queries);
2680
- }
2681
- }
2682
-
2683
- onSubscribe() {
2684
- if (this.listeners.length === 1) {
2685
- this.observers.forEach(observer => {
2686
- observer.subscribe(result => {
2687
- this.onUpdate(observer, result);
2688
- });
2689
- });
2690
- }
2691
- }
2692
-
2693
- onUnsubscribe() {
2694
- if (!this.listeners.length) {
2695
- this.destroy();
2696
- }
2697
- }
2698
-
2699
- destroy() {
2700
- this.listeners = [];
2701
- this.observers.forEach(observer => {
2702
- observer.destroy();
2703
- });
2704
- }
2705
-
2706
- setQueries(queries, notifyOptions) {
2707
- this.queries = queries;
2708
- notifyManager.batch(() => {
2709
- const prevObservers = this.observers;
2710
- const newObserverMatches = this.findMatchingObservers(this.queries); // set options for the new observers to notify of changes
2711
-
2712
- newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2713
- const newObservers = newObserverMatches.map(match => match.observer);
2714
- const newObserversMap = Object.fromEntries(newObservers.map(observer => [observer.options.queryHash, observer]));
2715
- const newResult = newObservers.map(observer => observer.getCurrentResult());
2716
- const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2717
-
2718
- if (prevObservers.length === newObservers.length && !hasIndexChange) {
2719
- return;
2720
- }
2721
-
2722
- this.observers = newObservers;
2723
- this.observersMap = newObserversMap;
2724
- this.result = newResult;
2725
-
2726
- if (!this.hasListeners()) {
2727
- return;
2728
- }
2729
-
2730
- difference(prevObservers, newObservers).forEach(observer => {
2731
- observer.destroy();
2732
- });
2733
- difference(newObservers, prevObservers).forEach(observer => {
2734
- observer.subscribe(result => {
2735
- this.onUpdate(observer, result);
2736
- });
2737
- });
2738
- this.notify();
2739
- });
2740
- }
2741
-
2742
- getCurrentResult() {
2743
- return this.result;
2744
- }
2745
-
2746
- getOptimisticResult(queries) {
2747
- return this.findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2748
- }
2749
-
2750
- findMatchingObservers(queries) {
2751
- const prevObservers = this.observers;
2752
- const defaultedQueryOptions = queries.map(options => this.client.defaultQueryOptions(options));
2753
- const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2754
- const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash);
2755
-
2756
- if (match != null) {
2757
- return [{
2758
- defaultedQueryOptions: defaultedOptions,
2759
- observer: match
2760
- }];
2761
- }
2762
-
2763
- return [];
2764
- });
2765
- const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash);
2766
- const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash));
2767
- const unmatchedObservers = prevObservers.filter(prevObserver => !matchingObservers.some(match => match.observer === prevObserver));
2768
-
2769
- const getObserver = options => {
2770
- const defaultedOptions = this.client.defaultQueryOptions(options);
2771
- const currentObserver = this.observersMap[defaultedOptions.queryHash];
2772
- return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
2773
- };
2774
-
2775
- const newOrReusedObservers = unmatchedQueries.map((options, index) => {
2776
- if (options.keepPreviousData) {
2777
- // return previous data from one of the observers that no longer match
2778
- const previouslyUsedObserver = unmatchedObservers[index];
2779
-
2780
- if (previouslyUsedObserver !== undefined) {
2781
- return {
2782
- defaultedQueryOptions: options,
2783
- observer: previouslyUsedObserver
2784
- };
2785
- }
2786
- }
2787
-
2788
- return {
2789
- defaultedQueryOptions: options,
2790
- observer: getObserver(options)
2791
- };
2792
- });
2793
-
2794
- const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
2795
-
2796
- return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
2797
- }
2798
-
2799
- onUpdate(observer, result) {
2800
- const index = this.observers.indexOf(observer);
2801
-
2802
- if (index !== -1) {
2803
- this.result = replaceAt(this.result, index, result);
2804
- this.notify();
2805
- }
2806
- }
2807
-
2808
- notify() {
2809
- notifyManager.batch(() => {
2810
- this.listeners.forEach(listener => {
2811
- listener(this.result);
2812
- });
2813
- });
2814
- }
2815
-
2816
- }
2817
-
2818
- class InfiniteQueryObserver extends QueryObserver {
2819
- // Type override
2820
- // Type override
2821
- // Type override
2822
- // eslint-disable-next-line @typescript-eslint/no-useless-constructor
2823
- constructor(client, options) {
2824
- super(client, options);
2825
- }
2826
-
2827
- bindMethods() {
2828
- super.bindMethods();
2829
- this.fetchNextPage = this.fetchNextPage.bind(this);
2830
- this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
2831
- }
2832
-
2833
- setOptions(options, notifyOptions) {
2834
- super.setOptions({ ...options,
2835
- behavior: infiniteQueryBehavior()
2836
- }, notifyOptions);
2837
- }
2838
-
2839
- getOptimisticResult(options) {
2840
- options.behavior = infiniteQueryBehavior();
2841
- return super.getOptimisticResult(options);
2842
- }
2843
-
2844
- fetchNextPage({
2845
- pageParam,
2846
- ...options
2847
- } = {}) {
2848
- return this.fetch({ ...options,
2849
- meta: {
2850
- fetchMore: {
2851
- direction: 'forward',
2852
- pageParam
2853
- }
2854
- }
2855
- });
2856
- }
2857
-
2858
- fetchPreviousPage({
2859
- pageParam,
2860
- ...options
2861
- } = {}) {
2862
- return this.fetch({ ...options,
2863
- meta: {
2864
- fetchMore: {
2865
- direction: 'backward',
2866
- pageParam
2867
- }
2868
- }
2869
- });
2870
- }
2871
-
2872
- createResult(query, options) {
2873
- var _state$data, _state$data2, _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet;
2874
-
2875
- const {
2876
- state
2877
- } = query;
2878
- const result = super.createResult(query, options);
2879
- return { ...result,
2880
- fetchNextPage: this.fetchNextPage,
2881
- fetchPreviousPage: this.fetchPreviousPage,
2882
- hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
2883
- hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
2884
- isFetchingNextPage: state.fetchStatus === 'fetching' && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward',
2885
- isFetchingPreviousPage: state.fetchStatus === 'fetching' && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward'
2886
- };
2887
- }
2888
-
2889
- }
2890
-
2891
- // CLASS
2892
- class MutationObserver extends Subscribable {
2893
- constructor(client, options) {
2894
- super();
2895
- this.client = client;
2896
- this.setOptions(options);
2897
- this.bindMethods();
2898
- this.updateResult();
2899
- }
2900
-
2901
- bindMethods() {
2902
- this.mutate = this.mutate.bind(this);
2903
- this.reset = this.reset.bind(this);
2904
- }
2905
-
2906
- setOptions(options) {
2907
- const prevOptions = this.options;
2908
- this.options = this.client.defaultMutationOptions(options);
2909
-
2910
- if (!shallowEqualObjects(prevOptions, this.options)) {
2911
- this.client.getMutationCache().notify({
2912
- type: 'observerOptionsUpdated',
2913
- mutation: this.currentMutation,
2914
- observer: this
2915
- });
2916
- }
2917
- }
2918
-
2919
- onUnsubscribe() {
2920
- if (!this.listeners.length) {
2921
- var _this$currentMutation;
2922
-
2923
- (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
2924
- }
2925
- }
2926
-
2927
- onMutationUpdate(action) {
2928
- this.updateResult(); // Determine which callbacks to trigger
2929
-
2930
- const notifyOptions = {
2931
- listeners: true
2932
- };
2933
-
2934
- if (action.type === 'success') {
2935
- notifyOptions.onSuccess = true;
2936
- } else if (action.type === 'error') {
2937
- notifyOptions.onError = true;
2938
- }
2939
-
2940
- this.notify(notifyOptions);
2941
- }
2942
-
2943
- getCurrentResult() {
2944
- return this.currentResult;
2945
- }
2946
-
2947
- reset() {
2948
- this.currentMutation = undefined;
2949
- this.updateResult();
2950
- this.notify({
2951
- listeners: true
2952
- });
2953
- }
2954
-
2955
- mutate(variables, options) {
2956
- this.mutateOptions = options;
2957
-
2958
- if (this.currentMutation) {
2959
- this.currentMutation.removeObserver(this);
2960
- }
2961
-
2962
- this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
2963
- variables: typeof variables !== 'undefined' ? variables : this.options.variables
2964
- });
2965
- this.currentMutation.addObserver(this);
2966
- return this.currentMutation.execute();
2967
- }
2968
-
2969
- updateResult() {
2970
- const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
2971
- const result = { ...state,
2972
- isLoading: state.status === 'loading',
2973
- isSuccess: state.status === 'success',
2974
- isError: state.status === 'error',
2975
- isIdle: state.status === 'idle',
2976
- mutate: this.mutate,
2977
- reset: this.reset
2978
- };
2979
- this.currentResult = result;
2980
- }
2981
-
2982
- notify(options) {
2983
- notifyManager.batch(() => {
2984
- // First trigger the mutate callbacks
2985
- if (this.mutateOptions) {
2986
- if (options.onSuccess) {
2987
- var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
2988
-
2989
- (_this$mutateOptions$o = (_this$mutateOptions = this.mutateOptions).onSuccess) == null ? void 0 : _this$mutateOptions$o.call(_this$mutateOptions, this.currentResult.data, this.currentResult.variables, this.currentResult.context);
2990
- (_this$mutateOptions$o2 = (_this$mutateOptions2 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o2.call(_this$mutateOptions2, this.currentResult.data, null, this.currentResult.variables, this.currentResult.context);
2991
- } else if (options.onError) {
2992
- var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
2993
-
2994
- (_this$mutateOptions$o3 = (_this$mutateOptions3 = this.mutateOptions).onError) == null ? void 0 : _this$mutateOptions$o3.call(_this$mutateOptions3, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
2995
- (_this$mutateOptions$o4 = (_this$mutateOptions4 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o4.call(_this$mutateOptions4, undefined, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
2996
- }
2997
- } // Then trigger the listeners
2998
-
2999
-
3000
- if (options.listeners) {
3001
- this.listeners.forEach(listener => {
3002
- listener(this.currentResult);
3003
- });
3004
- }
3005
- });
3006
- }
3007
-
3008
- }
3009
-
3010
- // TYPES
3011
- // FUNCTIONS
3012
- function dehydrateMutation(mutation) {
3013
- return {
3014
- mutationKey: mutation.options.mutationKey,
3015
- state: mutation.state
3016
- };
3017
- } // Most config is not dehydrated but instead meant to configure again when
3018
- // consuming the de/rehydrated data, typically with useQuery on the client.
3019
- // Sometimes it might make sense to prefetch data on the server and include
3020
- // in the html-payload, but not consume it on the initial render.
3021
-
3022
-
3023
- function dehydrateQuery(query) {
3024
- return {
3025
- state: query.state,
3026
- queryKey: query.queryKey,
3027
- queryHash: query.queryHash
3028
- };
3029
- }
3030
-
3031
- function defaultShouldDehydrateMutation(mutation) {
3032
- return mutation.state.isPaused;
3033
- }
3034
-
3035
- function defaultShouldDehydrateQuery(query) {
3036
- return query.state.status === 'success';
3037
- }
3038
-
3039
- function dehydrate(client, options = {}) {
3040
- const mutations = [];
3041
- const queries = [];
3042
-
3043
- if (options.dehydrateMutations !== false) {
3044
- const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
3045
- client.getMutationCache().getAll().forEach(mutation => {
3046
- if (shouldDehydrateMutation(mutation)) {
3047
- mutations.push(dehydrateMutation(mutation));
3048
- }
3049
- });
3050
- }
3051
-
3052
- if (options.dehydrateQueries !== false) {
3053
- const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
3054
- client.getQueryCache().getAll().forEach(query => {
3055
- if (shouldDehydrateQuery(query)) {
3056
- queries.push(dehydrateQuery(query));
3057
- }
3058
- });
3059
- }
3060
-
3061
- return {
3062
- mutations,
3063
- queries
3064
- };
3065
- }
3066
- function hydrate(client, dehydratedState, options) {
3067
- if (typeof dehydratedState !== 'object' || dehydratedState === null) {
3068
- return;
3069
- }
3070
-
3071
- const mutationCache = client.getMutationCache();
3072
- const queryCache = client.getQueryCache(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3073
-
3074
- const mutations = dehydratedState.mutations || []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3075
-
3076
- const queries = dehydratedState.queries || [];
3077
- mutations.forEach(dehydratedMutation => {
3078
- var _options$defaultOptio;
3079
-
3080
- mutationCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations),
3081
- mutationKey: dehydratedMutation.mutationKey
3082
- }, dehydratedMutation.state);
3083
- });
3084
- queries.forEach(dehydratedQuery => {
3085
- var _options$defaultOptio2;
3086
-
3087
- const query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
3088
-
3089
- if (query) {
3090
- if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
3091
- query.setState(dehydratedQuery.state);
3092
- }
3093
-
3094
- return;
3095
- } // Restore query
3096
-
3097
-
3098
- queryCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries),
3099
- queryKey: dehydratedQuery.queryKey,
3100
- queryHash: dehydratedQuery.queryHash
3101
- }, dehydratedQuery.state);
3102
- });
3103
- }
3104
-
3105
- exports.CancelledError = CancelledError;
3106
- exports.InfiniteQueryObserver = InfiniteQueryObserver;
3107
- exports.MutationCache = MutationCache;
3108
- exports.MutationObserver = MutationObserver;
3109
- exports.QueriesObserver = QueriesObserver;
3110
- exports.QueryCache = QueryCache;
3111
- exports.QueryClient = QueryClient;
3112
- exports.QueryObserver = QueryObserver;
3113
- exports.dehydrate = dehydrate;
3114
- exports.focusManager = focusManager;
3115
- exports.hashQueryKey = hashQueryKey;
3116
- exports.hydrate = hydrate;
3117
- exports.isCancelledError = isCancelledError;
3118
- exports.isError = isError;
3119
- exports.notifyManager = notifyManager;
3120
- exports.onlineManager = onlineManager;
3121
- exports.parseFilterArgs = parseFilterArgs;
3122
- exports.parseMutationArgs = parseMutationArgs;
3123
- exports.parseMutationFilterArgs = parseMutationFilterArgs;
3124
- exports.parseQueryArgs = parseQueryArgs;
3125
- //# sourceMappingURL=index.js.map