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