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