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

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