@tanstack/react-query 4.1.3 → 4.3.0-beta.1

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