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