@tanstack/query-core 5.102.7 → 5.103.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.
- package/build/legacy/environmentManager.cjs +15 -1
- package/build/legacy/environmentManager.cjs.map +1 -1
- package/build/legacy/environmentManager.d.cts +15 -1
- package/build/legacy/environmentManager.d.cts.map +1 -1
- package/build/legacy/environmentManager.d.ts +15 -1
- package/build/legacy/environmentManager.d.ts.map +1 -1
- package/build/legacy/environmentManager.js +15 -1
- package/build/legacy/environmentManager.js.map +1 -1
- package/build/legacy/focusManager.cjs +57 -0
- package/build/legacy/focusManager.cjs.map +1 -1
- package/build/legacy/focusManager.d.cts +57 -0
- package/build/legacy/focusManager.d.cts.map +1 -1
- package/build/legacy/focusManager.d.ts +57 -0
- package/build/legacy/focusManager.d.ts.map +1 -1
- package/build/legacy/focusManager.js +57 -0
- package/build/legacy/focusManager.js.map +1 -1
- package/build/legacy/{hydration-Bjs0MSgg.d.ts → hydration-Cq7QYAzB.d.ts} +1424 -7
- package/build/legacy/hydration-Cq7QYAzB.d.ts.map +1 -0
- package/build/legacy/{hydration-DWGr3cFC.d.cts → hydration-DwR10Hi-.d.cts} +1424 -7
- package/build/legacy/hydration-DwR10Hi-.d.cts.map +1 -0
- package/build/legacy/hydration.cjs +57 -4
- package/build/legacy/hydration.cjs.map +1 -1
- package/build/legacy/hydration.d.cts +1 -1
- package/build/legacy/hydration.d.ts +1 -1
- package/build/legacy/hydration.js +57 -4
- package/build/legacy/hydration.js.map +1 -1
- package/build/legacy/index.cjs.map +1 -1
- package/build/legacy/index.d.cts +5 -5
- package/build/legacy/index.d.ts +5 -5
- package/build/legacy/index.js.map +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
- package/build/legacy/infiniteQueryObserver.cjs +67 -0
- package/build/legacy/infiniteQueryObserver.cjs.map +1 -1
- package/build/legacy/infiniteQueryObserver.d.cts +68 -1
- package/build/legacy/infiniteQueryObserver.d.cts.map +1 -1
- package/build/legacy/infiniteQueryObserver.d.ts +68 -1
- package/build/legacy/infiniteQueryObserver.d.ts.map +1 -1
- package/build/legacy/infiniteQueryObserver.js +67 -0
- package/build/legacy/infiniteQueryObserver.js.map +1 -1
- package/build/legacy/mutation.cjs +74 -0
- package/build/legacy/mutation.cjs.map +1 -1
- package/build/legacy/mutation.d.cts +1 -1
- package/build/legacy/mutation.d.ts +1 -1
- package/build/legacy/mutation.js +74 -0
- package/build/legacy/mutation.js.map +1 -1
- package/build/legacy/mutationCache.cjs +74 -0
- package/build/legacy/mutationCache.cjs.map +1 -1
- package/build/legacy/mutationCache.d.cts +1 -1
- package/build/legacy/mutationCache.d.ts +1 -1
- package/build/legacy/mutationCache.js +74 -0
- package/build/legacy/mutationCache.js.map +1 -1
- package/build/legacy/mutationObserver.cjs +71 -0
- package/build/legacy/mutationObserver.cjs.map +1 -1
- package/build/legacy/mutationObserver.d.cts +1 -1
- package/build/legacy/mutationObserver.d.ts +1 -1
- package/build/legacy/mutationObserver.js +71 -0
- package/build/legacy/mutationObserver.js.map +1 -1
- package/build/legacy/notifyManager.cjs +45 -1
- package/build/legacy/notifyManager.cjs.map +1 -1
- package/build/legacy/notifyManager.d.cts +83 -2
- package/build/legacy/notifyManager.d.cts.map +1 -1
- package/build/legacy/notifyManager.d.ts +83 -2
- package/build/legacy/notifyManager.d.ts.map +1 -1
- package/build/legacy/notifyManager.js +45 -1
- package/build/legacy/notifyManager.js.map +1 -1
- package/build/legacy/onlineManager.cjs +47 -0
- package/build/legacy/onlineManager.cjs.map +1 -1
- package/build/legacy/onlineManager.d.cts +47 -0
- package/build/legacy/onlineManager.d.cts.map +1 -1
- package/build/legacy/onlineManager.d.ts +47 -0
- package/build/legacy/onlineManager.d.ts.map +1 -1
- package/build/legacy/onlineManager.js +47 -0
- package/build/legacy/onlineManager.js.map +1 -1
- package/build/legacy/queriesObserver.cjs +64 -0
- package/build/legacy/queriesObserver.cjs.map +1 -1
- package/build/legacy/queriesObserver.d.cts +73 -1
- package/build/legacy/queriesObserver.d.cts.map +1 -1
- package/build/legacy/queriesObserver.d.ts +73 -1
- package/build/legacy/queriesObserver.d.ts.map +1 -1
- package/build/legacy/queriesObserver.js +64 -0
- package/build/legacy/queriesObserver.js.map +1 -1
- package/build/legacy/query.cjs +141 -0
- package/build/legacy/query.cjs.map +1 -1
- package/build/legacy/query.d.cts +1 -1
- package/build/legacy/query.d.ts +1 -1
- package/build/legacy/query.js +141 -0
- package/build/legacy/query.js.map +1 -1
- package/build/legacy/queryCache.cjs +120 -0
- package/build/legacy/queryCache.cjs.map +1 -1
- package/build/legacy/queryCache.d.cts +1 -1
- package/build/legacy/queryCache.d.ts +1 -1
- package/build/legacy/queryCache.js +120 -0
- package/build/legacy/queryCache.js.map +1 -1
- package/build/legacy/queryClient.cjs +363 -0
- package/build/legacy/queryClient.cjs.map +1 -1
- package/build/legacy/queryClient.d.cts +1 -1
- package/build/legacy/queryClient.d.ts +1 -1
- package/build/legacy/queryClient.js +363 -0
- package/build/legacy/queryClient.js.map +1 -1
- package/build/legacy/queryObserver.cjs +116 -2
- package/build/legacy/queryObserver.cjs.map +1 -1
- package/build/legacy/queryObserver.d.cts +1 -1
- package/build/legacy/queryObserver.d.ts +1 -1
- package/build/legacy/queryObserver.js +116 -2
- package/build/legacy/queryObserver.js.map +1 -1
- package/build/legacy/retryer.cjs +18 -0
- package/build/legacy/retryer.cjs.map +1 -1
- package/build/legacy/retryer.d.cts +1 -1
- package/build/legacy/retryer.d.ts +1 -1
- package/build/legacy/retryer.js +18 -0
- package/build/legacy/retryer.js.map +1 -1
- package/build/legacy/streamedQuery.cjs +10 -1
- package/build/legacy/streamedQuery.cjs.map +1 -1
- package/build/legacy/streamedQuery.d.cts +26 -2
- package/build/legacy/streamedQuery.d.cts.map +1 -1
- package/build/legacy/streamedQuery.d.ts +26 -2
- package/build/legacy/streamedQuery.d.ts.map +1 -1
- package/build/legacy/streamedQuery.js +10 -1
- package/build/legacy/streamedQuery.js.map +1 -1
- package/build/legacy/timeoutManager.cjs +99 -0
- package/build/legacy/timeoutManager.cjs.map +1 -1
- package/build/legacy/timeoutManager.d.cts +105 -0
- package/build/legacy/timeoutManager.d.cts.map +1 -1
- package/build/legacy/timeoutManager.d.ts +105 -0
- package/build/legacy/timeoutManager.d.ts.map +1 -1
- package/build/legacy/timeoutManager.js +99 -0
- package/build/legacy/timeoutManager.js.map +1 -1
- package/build/legacy/types.cjs.map +1 -1
- package/build/legacy/types.d.cts +1 -1
- package/build/legacy/types.d.ts +1 -1
- package/build/legacy/types.js.map +1 -1
- package/build/legacy/utils.cjs +76 -0
- package/build/legacy/utils.cjs.map +1 -1
- package/build/legacy/utils.d.cts +1 -1
- package/build/legacy/utils.d.ts +1 -1
- package/build/legacy/utils.js +76 -0
- package/build/legacy/utils.js.map +1 -1
- package/build/modern/environmentManager.cjs +15 -1
- package/build/modern/environmentManager.cjs.map +1 -1
- package/build/modern/environmentManager.d.cts +15 -1
- package/build/modern/environmentManager.d.cts.map +1 -1
- package/build/modern/environmentManager.d.ts +15 -1
- package/build/modern/environmentManager.d.ts.map +1 -1
- package/build/modern/environmentManager.js +15 -1
- package/build/modern/environmentManager.js.map +1 -1
- package/build/modern/focusManager.cjs +57 -0
- package/build/modern/focusManager.cjs.map +1 -1
- package/build/modern/focusManager.d.cts +57 -0
- package/build/modern/focusManager.d.cts.map +1 -1
- package/build/modern/focusManager.d.ts +57 -0
- package/build/modern/focusManager.d.ts.map +1 -1
- package/build/modern/focusManager.js +57 -0
- package/build/modern/focusManager.js.map +1 -1
- package/build/modern/{hydration-Bjs0MSgg.d.ts → hydration-Cq7QYAzB.d.ts} +1424 -7
- package/build/modern/hydration-Cq7QYAzB.d.ts.map +1 -0
- package/build/modern/{hydration-DWGr3cFC.d.cts → hydration-DwR10Hi-.d.cts} +1424 -7
- package/build/modern/hydration-DwR10Hi-.d.cts.map +1 -0
- package/build/modern/hydration.cjs +57 -4
- package/build/modern/hydration.cjs.map +1 -1
- package/build/modern/hydration.d.cts +1 -1
- package/build/modern/hydration.d.ts +1 -1
- package/build/modern/hydration.js +57 -4
- package/build/modern/hydration.js.map +1 -1
- package/build/modern/index.cjs.map +1 -1
- package/build/modern/index.d.cts +5 -5
- package/build/modern/index.d.ts +5 -5
- package/build/modern/index.js.map +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts +1 -1
- package/build/modern/infiniteQueryObserver.cjs +67 -0
- package/build/modern/infiniteQueryObserver.cjs.map +1 -1
- package/build/modern/infiniteQueryObserver.d.cts +68 -1
- package/build/modern/infiniteQueryObserver.d.cts.map +1 -1
- package/build/modern/infiniteQueryObserver.d.ts +68 -1
- package/build/modern/infiniteQueryObserver.d.ts.map +1 -1
- package/build/modern/infiniteQueryObserver.js +67 -0
- package/build/modern/infiniteQueryObserver.js.map +1 -1
- package/build/modern/mutation.cjs +74 -0
- package/build/modern/mutation.cjs.map +1 -1
- package/build/modern/mutation.d.cts +1 -1
- package/build/modern/mutation.d.ts +1 -1
- package/build/modern/mutation.js +74 -0
- package/build/modern/mutation.js.map +1 -1
- package/build/modern/mutationCache.cjs +74 -0
- package/build/modern/mutationCache.cjs.map +1 -1
- package/build/modern/mutationCache.d.cts +1 -1
- package/build/modern/mutationCache.d.ts +1 -1
- package/build/modern/mutationCache.js +74 -0
- package/build/modern/mutationCache.js.map +1 -1
- package/build/modern/mutationObserver.cjs +71 -0
- package/build/modern/mutationObserver.cjs.map +1 -1
- package/build/modern/mutationObserver.d.cts +1 -1
- package/build/modern/mutationObserver.d.ts +1 -1
- package/build/modern/mutationObserver.js +71 -0
- package/build/modern/mutationObserver.js.map +1 -1
- package/build/modern/notifyManager.cjs +45 -1
- package/build/modern/notifyManager.cjs.map +1 -1
- package/build/modern/notifyManager.d.cts +83 -2
- package/build/modern/notifyManager.d.cts.map +1 -1
- package/build/modern/notifyManager.d.ts +83 -2
- package/build/modern/notifyManager.d.ts.map +1 -1
- package/build/modern/notifyManager.js +45 -1
- package/build/modern/notifyManager.js.map +1 -1
- package/build/modern/onlineManager.cjs +47 -0
- package/build/modern/onlineManager.cjs.map +1 -1
- package/build/modern/onlineManager.d.cts +47 -0
- package/build/modern/onlineManager.d.cts.map +1 -1
- package/build/modern/onlineManager.d.ts +47 -0
- package/build/modern/onlineManager.d.ts.map +1 -1
- package/build/modern/onlineManager.js +47 -0
- package/build/modern/onlineManager.js.map +1 -1
- package/build/modern/queriesObserver.cjs +64 -0
- package/build/modern/queriesObserver.cjs.map +1 -1
- package/build/modern/queriesObserver.d.cts +73 -1
- package/build/modern/queriesObserver.d.cts.map +1 -1
- package/build/modern/queriesObserver.d.ts +73 -1
- package/build/modern/queriesObserver.d.ts.map +1 -1
- package/build/modern/queriesObserver.js +64 -0
- package/build/modern/queriesObserver.js.map +1 -1
- package/build/modern/query.cjs +141 -0
- package/build/modern/query.cjs.map +1 -1
- package/build/modern/query.d.cts +1 -1
- package/build/modern/query.d.ts +1 -1
- package/build/modern/query.js +141 -0
- package/build/modern/query.js.map +1 -1
- package/build/modern/queryCache.cjs +120 -0
- package/build/modern/queryCache.cjs.map +1 -1
- package/build/modern/queryCache.d.cts +1 -1
- package/build/modern/queryCache.d.ts +1 -1
- package/build/modern/queryCache.js +120 -0
- package/build/modern/queryCache.js.map +1 -1
- package/build/modern/queryClient.cjs +363 -0
- package/build/modern/queryClient.cjs.map +1 -1
- package/build/modern/queryClient.d.cts +1 -1
- package/build/modern/queryClient.d.ts +1 -1
- package/build/modern/queryClient.js +363 -0
- package/build/modern/queryClient.js.map +1 -1
- package/build/modern/queryObserver.cjs +116 -2
- package/build/modern/queryObserver.cjs.map +1 -1
- package/build/modern/queryObserver.d.cts +1 -1
- package/build/modern/queryObserver.d.ts +1 -1
- package/build/modern/queryObserver.js +116 -2
- package/build/modern/queryObserver.js.map +1 -1
- package/build/modern/retryer.cjs +18 -0
- package/build/modern/retryer.cjs.map +1 -1
- package/build/modern/retryer.d.cts +1 -1
- package/build/modern/retryer.d.ts +1 -1
- package/build/modern/retryer.js +18 -0
- package/build/modern/retryer.js.map +1 -1
- package/build/modern/streamedQuery.cjs +10 -1
- package/build/modern/streamedQuery.cjs.map +1 -1
- package/build/modern/streamedQuery.d.cts +26 -2
- package/build/modern/streamedQuery.d.cts.map +1 -1
- package/build/modern/streamedQuery.d.ts +26 -2
- package/build/modern/streamedQuery.d.ts.map +1 -1
- package/build/modern/streamedQuery.js +10 -1
- package/build/modern/streamedQuery.js.map +1 -1
- package/build/modern/timeoutManager.cjs +99 -0
- package/build/modern/timeoutManager.cjs.map +1 -1
- package/build/modern/timeoutManager.d.cts +105 -0
- package/build/modern/timeoutManager.d.cts.map +1 -1
- package/build/modern/timeoutManager.d.ts +105 -0
- package/build/modern/timeoutManager.d.ts.map +1 -1
- package/build/modern/timeoutManager.js +99 -0
- package/build/modern/timeoutManager.js.map +1 -1
- package/build/modern/types.cjs.map +1 -1
- package/build/modern/types.d.cts +1 -1
- package/build/modern/types.d.ts +1 -1
- package/build/modern/types.js.map +1 -1
- package/build/modern/utils.cjs +76 -0
- package/build/modern/utils.cjs.map +1 -1
- package/build/modern/utils.d.cts +1 -1
- package/build/modern/utils.d.ts +1 -1
- package/build/modern/utils.js +76 -0
- package/build/modern/utils.js.map +1 -1
- package/package.json +9 -9
- package/src/environmentManager.ts +15 -1
- package/src/focusManager.ts +57 -0
- package/src/hydration.ts +82 -16
- package/src/index.ts +3 -0
- package/src/infiniteQueryObserver.ts +67 -0
- package/src/mutation.ts +108 -0
- package/src/mutationCache.ts +91 -0
- package/src/mutationObserver.ts +71 -0
- package/src/notifyManager.ts +46 -1
- package/src/onlineManager.ts +47 -0
- package/src/queriesObserver.ts +72 -0
- package/src/query.ts +193 -0
- package/src/queryCache.ts +134 -0
- package/src/queryClient.ts +369 -0
- package/src/queryObserver.ts +117 -4
- package/src/retryer.ts +18 -0
- package/src/streamedQuery.ts +25 -1
- package/src/timeoutManager.ts +105 -0
- package/src/types.ts +147 -5
- package/src/utils.ts +107 -0
- package/build/legacy/hydration-Bjs0MSgg.d.ts.map +0 -1
- package/build/legacy/hydration-DWGr3cFC.d.cts.map +0 -1
- package/build/modern/hydration-Bjs0MSgg.d.ts.map +0 -1
- package/build/modern/hydration-DWGr3cFC.d.cts.map +0 -1
package/build/legacy/query.js
CHANGED
|
@@ -15,6 +15,25 @@ var _retryer = /* @__PURE__ */ new WeakMap();
|
|
|
15
15
|
var _defaultOptions = /* @__PURE__ */ new WeakMap();
|
|
16
16
|
var _abortSignalConsumed = /* @__PURE__ */ new WeakMap();
|
|
17
17
|
var _Query_brand = /* @__PURE__ */ new WeakSet();
|
|
18
|
+
/**
|
|
19
|
+
* Represents a single cached query. A `Query` holds the query's key, options,
|
|
20
|
+
* state (data/error/status), and the observers currently subscribed to it.
|
|
21
|
+
*
|
|
22
|
+
* Instances are created and managed internally by `QueryCache`; application
|
|
23
|
+
* code typically interacts with queries indirectly through `QueryClient` or
|
|
24
|
+
* a framework hook like `useQuery`. Direct access to a `Query` instance is
|
|
25
|
+
* possible via `queryCache.find()`/`findAll()` for inspecting cache state.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const queryCache = queryClient.getQueryCache()
|
|
30
|
+
* const query = queryCache.find({ queryKey: ['posts'] })
|
|
31
|
+
*
|
|
32
|
+
* if (query) {
|
|
33
|
+
* console.log(query.state.dataUpdatedAt)
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
18
37
|
var Query = class extends Removable {
|
|
19
38
|
constructor(config) {
|
|
20
39
|
super();
|
|
@@ -39,16 +58,25 @@ var Query = class extends Removable {
|
|
|
39
58
|
this.state = config.state ?? _classPrivateFieldGet2(_initialState, this);
|
|
40
59
|
this.scheduleGc();
|
|
41
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* The `meta` object passed in the query's options, if any.
|
|
63
|
+
*/
|
|
42
64
|
get meta() {
|
|
43
65
|
return this.options.meta;
|
|
44
66
|
}
|
|
67
|
+
/** @internal */
|
|
45
68
|
get queryType() {
|
|
46
69
|
return _classPrivateFieldGet2(_queryType, this);
|
|
47
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* The promise for the currently in-flight fetch, if the query is fetching.
|
|
73
|
+
* `undefined` when the query is not fetching.
|
|
74
|
+
*/
|
|
48
75
|
get promise() {
|
|
49
76
|
var _classPrivateFieldGet2$1;
|
|
50
77
|
return (_classPrivateFieldGet2$1 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet2$1 === void 0 ? void 0 : _classPrivateFieldGet2$1.promise;
|
|
51
78
|
}
|
|
79
|
+
/** @internal */
|
|
52
80
|
setOptions(options) {
|
|
53
81
|
this.options = {
|
|
54
82
|
..._classPrivateFieldGet2(_defaultOptions, this),
|
|
@@ -67,6 +95,7 @@ var Query = class extends Removable {
|
|
|
67
95
|
optionalRemove() {
|
|
68
96
|
if (!this.observers.length && this.state.fetchStatus === "idle") _classPrivateFieldGet2(_cache, this).remove(this);
|
|
69
97
|
}
|
|
98
|
+
/** @internal */
|
|
70
99
|
setData(newData, options) {
|
|
71
100
|
const data = replaceData(this.state.data, newData, this.options);
|
|
72
101
|
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
|
@@ -77,65 +106,146 @@ var Query = class extends Removable {
|
|
|
77
106
|
});
|
|
78
107
|
return data;
|
|
79
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* Merges the given partial state directly into this query's state, notifying observers. Used
|
|
111
|
+
* by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a
|
|
112
|
+
* user manually trigger a loading/error state or edit the cached data.
|
|
113
|
+
*/
|
|
80
114
|
setState(state) {
|
|
81
115
|
_assertClassBrand(_Query_brand, this, _dispatch).call(this, {
|
|
82
116
|
type: "setState",
|
|
83
117
|
state
|
|
84
118
|
});
|
|
85
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Cancels the query's currently in-flight fetch, if any.
|
|
122
|
+
* - Returns a promise that resolves once the cancellation has settled.
|
|
123
|
+
* - If no fetch is in progress, resolves immediately.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* await query.cancel()
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
86
130
|
cancel(options) {
|
|
87
131
|
var _classPrivateFieldGet3, _classPrivateFieldGet4;
|
|
88
132
|
const promise = (_classPrivateFieldGet3 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet3 === void 0 ? void 0 : _classPrivateFieldGet3.promise;
|
|
89
133
|
(_classPrivateFieldGet4 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet4 === void 0 || _classPrivateFieldGet4.cancel(options);
|
|
90
134
|
return promise ? promise.then(noop).catch(noop) : Promise.resolve();
|
|
91
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Clears the query's garbage collection timeout and silently cancels any
|
|
138
|
+
* in-flight fetch. Called by `QueryCache` when the query is removed from
|
|
139
|
+
* the cache.
|
|
140
|
+
*
|
|
141
|
+
* @see {@link Query#cancel}
|
|
142
|
+
*/
|
|
92
143
|
destroy() {
|
|
93
144
|
super.destroy();
|
|
94
145
|
this.cancel({ silent: true });
|
|
95
146
|
}
|
|
147
|
+
/** @internal */
|
|
96
148
|
get resetState() {
|
|
97
149
|
return _classPrivateFieldGet2(_initialState, this);
|
|
98
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Resets the query back to its initial state (the state it had when it was
|
|
153
|
+
* first created, e.g. any `initialData`), destroying it first to cancel any
|
|
154
|
+
* in-flight fetch.
|
|
155
|
+
*/
|
|
99
156
|
reset() {
|
|
100
157
|
this.destroy();
|
|
101
158
|
this.setState(this.resetState);
|
|
102
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Returns `true` if the query has at least one observer for which `enabled`
|
|
162
|
+
* does not resolve to `false`.
|
|
163
|
+
*/
|
|
103
164
|
isActive() {
|
|
104
165
|
return this.observers.some((observer) => resolveQueryValue(observer.options.enabled, this) !== false);
|
|
105
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* Returns `true` if the query is disabled, meaning it will not fetch
|
|
169
|
+
* automatically.
|
|
170
|
+
* - If the query has observers, it is disabled when none of them are active
|
|
171
|
+
* (see `isActive`).
|
|
172
|
+
* - If the query has no observers, it is disabled when its `queryFn` is
|
|
173
|
+
* `skipToken` or it has never been fetched.
|
|
174
|
+
*/
|
|
106
175
|
isDisabled() {
|
|
107
176
|
if (this.getObserversCount() > 0) return !this.isActive();
|
|
108
177
|
return this.options.queryFn === skipToken || !this.isFetched();
|
|
109
178
|
}
|
|
179
|
+
/**
|
|
180
|
+
* Returns `true` if the query has been fetched, i.e. it has resolved with
|
|
181
|
+
* either data or an error at least once.
|
|
182
|
+
*/
|
|
110
183
|
isFetched() {
|
|
111
184
|
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
|
|
112
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Returns `true` if the query has at least one observer configured with
|
|
188
|
+
* `staleTime: 'static'`, meaning it is treated as never stale.
|
|
189
|
+
*/
|
|
113
190
|
isStatic() {
|
|
114
191
|
if (this.getObserversCount() > 0) return this.observers.some((observer) => resolveQueryValue(observer.options.staleTime, this) === "static");
|
|
115
192
|
return false;
|
|
116
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* Returns `true` if the query is stale.
|
|
196
|
+
* - If the query has observers, defers to whether any observer's current
|
|
197
|
+
* result reports `isStale` (which accounts for each observer's own
|
|
198
|
+
* `staleTime` and `enabled` state).
|
|
199
|
+
* - If the query has no observers, it is considered stale when it has no
|
|
200
|
+
* data or has been invalidated.
|
|
201
|
+
*
|
|
202
|
+
* @see {@link Query#isStaleByTime}
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* if (query.isStale()) {
|
|
206
|
+
* // refetch or otherwise treat the cached data as outdated
|
|
207
|
+
* }
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
117
210
|
isStale() {
|
|
118
211
|
if (this.getObserversCount() > 0) return this.observers.some((observer) => observer.getCurrentResult().isStale);
|
|
119
212
|
return this.state.data === void 0 || this.state.isInvalidated;
|
|
120
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Returns `true` if the query's data is stale relative to the given
|
|
216
|
+
* `staleTime` (defaults to `0`).
|
|
217
|
+
* - A query with no data is always stale.
|
|
218
|
+
* - `staleTime: 'static'` is never stale.
|
|
219
|
+
* - An invalidated query is always stale.
|
|
220
|
+
* - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.
|
|
221
|
+
*
|
|
222
|
+
* @see {@link Query#isStale}
|
|
223
|
+
* @example
|
|
224
|
+
* ```ts
|
|
225
|
+
* const isStale = query.isStaleByTime(1000 * 60)
|
|
226
|
+
* ```
|
|
227
|
+
*/
|
|
121
228
|
isStaleByTime(staleTime = 0) {
|
|
122
229
|
if (this.state.data === void 0) return true;
|
|
123
230
|
if (staleTime === "static") return false;
|
|
124
231
|
if (this.state.isInvalidated) return true;
|
|
125
232
|
return !timeUntilStale(this.state.dataUpdatedAt, staleTime);
|
|
126
233
|
}
|
|
234
|
+
/** @internal */
|
|
127
235
|
onFocus() {
|
|
128
236
|
var _classPrivateFieldGet5;
|
|
129
237
|
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
|
|
130
238
|
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
|
131
239
|
(_classPrivateFieldGet5 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet5 === void 0 || _classPrivateFieldGet5.continue();
|
|
132
240
|
}
|
|
241
|
+
/** @internal */
|
|
133
242
|
onOnline() {
|
|
134
243
|
var _classPrivateFieldGet6;
|
|
135
244
|
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
|
|
136
245
|
observer === null || observer === void 0 || observer.refetch({ cancelRefetch: false });
|
|
137
246
|
(_classPrivateFieldGet6 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet6 === void 0 || _classPrivateFieldGet6.continue();
|
|
138
247
|
}
|
|
248
|
+
/** @internal */
|
|
139
249
|
addObserver(observer) {
|
|
140
250
|
if (!this.observers.includes(observer)) {
|
|
141
251
|
this.observers.push(observer);
|
|
@@ -147,6 +257,7 @@ var Query = class extends Removable {
|
|
|
147
257
|
});
|
|
148
258
|
}
|
|
149
259
|
}
|
|
260
|
+
/** @internal */
|
|
150
261
|
removeObserver(observer) {
|
|
151
262
|
const index = this.observers.indexOf(observer);
|
|
152
263
|
if (index !== -1) {
|
|
@@ -165,12 +276,42 @@ var Query = class extends Removable {
|
|
|
165
276
|
});
|
|
166
277
|
}
|
|
167
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* Returns the number of observers currently subscribed to this query.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* ```ts
|
|
284
|
+
* if (query.getObserversCount() === 0) {
|
|
285
|
+
* // no component is currently watching this query
|
|
286
|
+
* }
|
|
287
|
+
* ```
|
|
288
|
+
*/
|
|
168
289
|
getObserversCount() {
|
|
169
290
|
return this.observers.length;
|
|
170
291
|
}
|
|
292
|
+
/**
|
|
293
|
+
* Marks the query as invalidated, unless it is already invalidated. This
|
|
294
|
+
* updates `state.isInvalidated` and notifies observers, but does not by
|
|
295
|
+
* itself trigger a refetch.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```ts
|
|
299
|
+
* query.invalidate()
|
|
300
|
+
* ```
|
|
301
|
+
*/
|
|
171
302
|
invalidate() {
|
|
172
303
|
if (!this.state.isInvalidated) _assertClassBrand(_Query_brand, this, _dispatch).call(this, { type: "invalidate" });
|
|
173
304
|
}
|
|
305
|
+
/**
|
|
306
|
+
* Fetches the query, i.e. runs its `queryFn` (through any configured
|
|
307
|
+
* retryer/behavior) and updates the query's state with the result.
|
|
308
|
+
* - If a fetch is already in flight, returns its promise instead of
|
|
309
|
+
* starting a new one, unless `fetchOptions.cancelRefetch` is set and the
|
|
310
|
+
* query already has data, in which case the current fetch is silently
|
|
311
|
+
* cancelled first.
|
|
312
|
+
* - If `options` is passed, it replaces the query's current options
|
|
313
|
+
* before fetching.
|
|
314
|
+
*/
|
|
174
315
|
async fetch(options, fetchOptions) {
|
|
175
316
|
var _classPrivateFieldGet7, _context$fetchOptions;
|
|
176
317
|
if (this.state.fetchStatus !== "idle" && ((_classPrivateFieldGet7 = _classPrivateFieldGet2(_retryer, this)) === null || _classPrivateFieldGet7 === void 0 ? void 0 : _classPrivateFieldGet7.status()) !== "rejected") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query.js","names":[],"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n data: TData | undefined\n dataUpdateCount: number\n dataUpdatedAt: number\n error: TError | null\n errorUpdateCount: number\n errorUpdatedAt: number\n fetchFailureCount: number\n fetchFailureReason: TError | null\n fetchMeta: FetchMeta | null\n isInvalidated: boolean\n status: QueryStatus\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n get queryType() {\n return this.#queryType\n }\n\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n isStatic(): boolean {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n getObserversCount(): number {\n return this.observers.length\n }\n\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `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']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n try {\n const data = await retryer.start()\n // this is more of a runtime guard\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n // silent cancellation implies a new fetch is going to be started,\n // so we piggyback onto that promise\n return this.#retryer.promise\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAyJA,IAAa,QAAb,cAKU,UAAU;CAgBlB,YAAY,QAA6D;EACvE,MAAM;;;;;;;;;;EAEN,uBAAA,sBAAA,MAA4B,KAAA;EAC5B,uBAAA,iBAAA,MAAuB,OAAO,cAAA;EAC9B,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,YAAY,CAAC;EAClB,uBAAA,SAAA,MAAe,OAAO,MAAA;EAC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AO;EACL;EACA,iBAAiB;EACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"query.js","names":[],"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n fetchFn: () => unknown | Promise<unknown>\n fetchOptions?: FetchOptions\n signal: AbortSignal\n options: QueryOptions<TQueryFnData, TError, TData, any>\n client: QueryClient\n queryKey: TQueryKey\n state: QueryState<TData, TError>\n}\n\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\nexport type FetchDirection = 'forward' | 'backward'\n\nexport interface FetchMeta {\n fetchMore?: { direction: FetchDirection }\n}\n\nexport interface FetchOptions<TData = unknown> {\n cancelRefetch?: boolean\n meta?: FetchMeta\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single cached query. A `Query` holds the query's key, options,\n * state (data/error/status), and the observers currently subscribed to it.\n *\n * Instances are created and managed internally by `QueryCache`; application\n * code typically interacts with queries indirectly through `QueryClient` or\n * a framework hook like `useQuery`. Direct access to a `Query` instance is\n * possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * console.log(query.state.dataUpdatedAt)\n * }\n * ```\n */\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n /**\n * The `meta` object passed in the query's options, if any.\n */\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n /** @internal */\n get queryType() {\n return this.#queryType\n }\n\n /**\n * The promise for the currently in-flight fetch, if the query is fetching.\n * `undefined` when the query is not fetching.\n */\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n /** @internal */\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n /** @internal */\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n /**\n * Merges the given partial state directly into this query's state, notifying observers. Used\n * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n * user manually trigger a loading/error state or edit the cached data.\n */\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n /**\n * Cancels the query's currently in-flight fetch, if any.\n * - Returns a promise that resolves once the cancellation has settled.\n * - If no fetch is in progress, resolves immediately.\n *\n * @example\n * ```ts\n * await query.cancel()\n * ```\n */\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n /**\n * Clears the query's garbage collection timeout and silently cancels any\n * in-flight fetch. Called by `QueryCache` when the query is removed from\n * the cache.\n *\n * @see {@link Query#cancel}\n */\n destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n /** @internal */\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n /**\n * Resets the query back to its initial state (the state it had when it was\n * first created, e.g. any `initialData`), destroying it first to cancel any\n * in-flight fetch.\n */\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n /**\n * Returns `true` if the query has at least one observer for which `enabled`\n * does not resolve to `false`.\n */\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n /**\n * Returns `true` if the query is disabled, meaning it will not fetch\n * automatically.\n * - If the query has observers, it is disabled when none of them are active\n * (see `isActive`).\n * - If the query has no observers, it is disabled when its `queryFn` is\n * `skipToken` or it has never been fetched.\n */\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n /**\n * Returns `true` if the query has been fetched, i.e. it has resolved with\n * either data or an error at least once.\n */\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n /**\n * Returns `true` if the query has at least one observer configured with\n * `staleTime: 'static'`, meaning it is treated as never stale.\n */\n isStatic(): boolean {\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n /**\n * Returns `true` if the query is stale.\n * - If the query has observers, defers to whether any observer's current\n * result reports `isStale` (which accounts for each observer's own\n * `staleTime` and `enabled` state).\n * - If the query has no observers, it is considered stale when it has no\n * data or has been invalidated.\n *\n * @see {@link Query#isStaleByTime}\n * @example\n * ```ts\n * if (query.isStale()) {\n * // refetch or otherwise treat the cached data as outdated\n * }\n * ```\n */\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n /**\n * Returns `true` if the query's data is stale relative to the given\n * `staleTime` (defaults to `0`).\n * - A query with no data is always stale.\n * - `staleTime: 'static'` is never stale.\n * - An invalidated query is always stale.\n * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n *\n * @see {@link Query#isStale}\n * @example\n * ```ts\n * const isStale = query.isStaleByTime(1000 * 60)\n * ```\n */\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n /** @internal */\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /** @internal */\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /** @internal */\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n /** @internal */\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n /**\n * Returns the number of observers currently subscribed to this query.\n *\n * @example\n * ```ts\n * if (query.getObserversCount() === 0) {\n * // no component is currently watching this query\n * }\n * ```\n */\n getObserversCount(): number {\n return this.observers.length\n }\n\n /**\n * Marks the query as invalidated, unless it is already invalidated. This\n * updates `state.isInvalidated` and notifies observers, but does not by\n * itself trigger a refetch.\n *\n * @example\n * ```ts\n * query.invalidate()\n * ```\n */\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n /**\n * Fetches the query, i.e. runs its `queryFn` (through any configured\n * retryer/behavior) and updates the query's state with the result.\n * - If a fetch is already in flight, returns its promise instead of\n * starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n * query already has data, in which case the current fetch is silently\n * cancelled first.\n * - If `options` is passed, it replaces the query's current options\n * before fetching.\n */\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#retryer.promise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `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']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: unknown) => {\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n try {\n const data = await retryer.start()\n // this is more of a runtime guard\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n // silent cancellation implies a new fetch is going to be started,\n // so we piggyback onto that promise\n return this.#retryer.promise\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;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AC1D,GAAI,SAAS,KAAA,KACV;GACC,OAAO;GACP,QAAQ;EACV;CACJ;AACF;AAEA,SAAS,aAAoB,MAAyB,eAAwB;CAC5E,OAAO;EACL;EACA,eAAe,iBAAiB,KAAK,IAAI;EACzC,OAAO;EACP,eAAe;EACf,QAAQ;CACV;AACF;AAEA,SAAS,gBAMP,SAC2B;CAC3B,MAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;CAEd,MAAM,UAAU,SAAS,KAAA;CAEzB,MAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;CAEJ,OAAO;EACL;EACA,iBAAiB;EACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
|
|
@@ -6,6 +6,23 @@ const require_notifyManager = require("./notifyManager.cjs");
|
|
|
6
6
|
const require_query = require("./query.cjs");
|
|
7
7
|
//#region src/queryCache.ts
|
|
8
8
|
var _queries = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
/**
|
|
10
|
+
* The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta
|
|
11
|
+
* information, and state of the queries it contains.
|
|
12
|
+
*
|
|
13
|
+
* Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`
|
|
14
|
+
* for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of
|
|
15
|
+
* safe/known updates to the cache, such as queries being added, removed, or updated — updates made
|
|
16
|
+
* outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do
|
|
17
|
+
* not notify subscribers.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```ts
|
|
21
|
+
* const unsubscribe = queryCache.subscribe((event) => {
|
|
22
|
+
* console.log(event.type, event.query)
|
|
23
|
+
* })
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
9
26
|
var QueryCache = class extends require_subscribable.Subscribable {
|
|
10
27
|
constructor(config = {}) {
|
|
11
28
|
super();
|
|
@@ -13,6 +30,22 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
13
30
|
require_classPrivateFieldSet2._classPrivateFieldInitSpec(this, _queries, void 0);
|
|
14
31
|
require_classPrivateFieldSet2._classPrivateFieldSet2(_queries, this, /* @__PURE__ */ new Map());
|
|
15
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or
|
|
35
|
+
* builds and adds a new one to the cache if none exists yet. Used by framework adapters and
|
|
36
|
+
* plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing
|
|
37
|
+
* the reactive `QueryObserver` machinery.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* const queryCache = queryClient.getQueryCache()
|
|
42
|
+
*
|
|
43
|
+
* const query = queryCache.build(queryClient, {
|
|
44
|
+
* queryKey: ['posts'],
|
|
45
|
+
* queryFn: fetchPosts,
|
|
46
|
+
* })
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
16
49
|
build(client, options, state) {
|
|
17
50
|
const queryKey = options.queryKey;
|
|
18
51
|
const queryHash = options.queryHash ?? require_utils.hashQueryKeyByOptions(queryKey, options);
|
|
@@ -30,6 +63,7 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
30
63
|
}
|
|
31
64
|
return query;
|
|
32
65
|
}
|
|
66
|
+
/** @internal */
|
|
33
67
|
add(query) {
|
|
34
68
|
if (!require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this).has(query.queryHash)) {
|
|
35
69
|
require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this).set(query.queryHash, query);
|
|
@@ -39,6 +73,22 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
39
73
|
});
|
|
40
74
|
}
|
|
41
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Destroys the given `Query` and removes it from the cache, notifying subscribers with a
|
|
78
|
+
* `'removed'` event. A no-op if the query is no longer the one currently stored under its hash
|
|
79
|
+
* (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror
|
|
80
|
+
* removals across `QueryCache` instances.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```ts
|
|
84
|
+
* const queryCache = queryClient.getQueryCache()
|
|
85
|
+
* const query = queryCache.find({ queryKey: ['posts'] })
|
|
86
|
+
*
|
|
87
|
+
* if (query) {
|
|
88
|
+
* queryCache.remove(query)
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
42
92
|
remove(query) {
|
|
43
93
|
const queryInMap = require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this).get(query.queryHash);
|
|
44
94
|
if (queryInMap) {
|
|
@@ -50,6 +100,16 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
50
100
|
});
|
|
51
101
|
}
|
|
52
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Removes all queries from the cache.
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```ts
|
|
108
|
+
* const queryCache = queryClient.getQueryCache()
|
|
109
|
+
*
|
|
110
|
+
* queryCache.clear()
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
53
113
|
clear() {
|
|
54
114
|
require_notifyManager.notifyManager.batch(() => {
|
|
55
115
|
this.getAll().forEach((query) => {
|
|
@@ -57,12 +117,54 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
57
117
|
});
|
|
58
118
|
});
|
|
59
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none
|
|
122
|
+
* exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather
|
|
123
|
+
* than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash
|
|
124
|
+
* to look up directly.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```ts
|
|
128
|
+
* const queryCache = queryClient.getQueryCache()
|
|
129
|
+
* const queryHash = hashKey(['posts'])
|
|
130
|
+
*
|
|
131
|
+
* const query = queryCache.get(queryHash)
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
60
134
|
get(queryHash) {
|
|
61
135
|
return require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this).get(queryHash);
|
|
62
136
|
}
|
|
137
|
+
/**
|
|
138
|
+
* Returns all queries within the cache.
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* const queryCache = queryClient.getQueryCache()
|
|
143
|
+
*
|
|
144
|
+
* const queries = queryCache.getAll()
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
63
147
|
getAll() {
|
|
64
148
|
return [...require_classPrivateFieldSet2._classPrivateFieldGet2(_queries, this).values()];
|
|
65
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* A slightly more advanced method that can be used to get an existing query instance from the
|
|
152
|
+
* cache. This instance not only contains all the state for the query, but all of the instances,
|
|
153
|
+
* and underlying guts of the query as well. If the query does not exist, `undefined` is
|
|
154
|
+
* returned.
|
|
155
|
+
*
|
|
156
|
+
* This is not typically needed for most applications, but can come in handy when needing more
|
|
157
|
+
* information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to
|
|
158
|
+
* decide whether a query is fresh enough to be used as an initial value).
|
|
159
|
+
*
|
|
160
|
+
* @see {@link QueryCache#findAll}
|
|
161
|
+
* @example
|
|
162
|
+
* ```ts
|
|
163
|
+
* const queryCache = queryClient.getQueryCache()
|
|
164
|
+
*
|
|
165
|
+
* const query = queryCache.find({ queryKey: ['posts'] })
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
66
168
|
find(filters) {
|
|
67
169
|
const defaultedFilters = {
|
|
68
170
|
exact: true,
|
|
@@ -70,10 +172,26 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
70
172
|
};
|
|
71
173
|
return this.getAll().find((query) => require_utils.matchQuery(defaultedFilters, query));
|
|
72
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* An even more advanced method that can be used to get existing query instances from the cache
|
|
177
|
+
* that partially match a query key. If no queries match, an empty array is returned.
|
|
178
|
+
*
|
|
179
|
+
* This is not typically needed for most applications, but can come in handy when needing more
|
|
180
|
+
* information about queries in rare scenarios.
|
|
181
|
+
*
|
|
182
|
+
* @see {@link QueryCache#find}
|
|
183
|
+
* @example
|
|
184
|
+
* ```ts
|
|
185
|
+
* const queryCache = queryClient.getQueryCache()
|
|
186
|
+
*
|
|
187
|
+
* const queries = queryCache.findAll({ queryKey: ['posts'] })
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
73
190
|
findAll(filters = {}) {
|
|
74
191
|
const queries = this.getAll();
|
|
75
192
|
return Object.keys(filters).length > 0 ? queries.filter((query) => require_utils.matchQuery(filters, query)) : queries;
|
|
76
193
|
}
|
|
194
|
+
/** @internal */
|
|
77
195
|
notify(event) {
|
|
78
196
|
require_notifyManager.notifyManager.batch(() => {
|
|
79
197
|
this.listeners.forEach((listener) => {
|
|
@@ -81,6 +199,7 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
81
199
|
});
|
|
82
200
|
});
|
|
83
201
|
}
|
|
202
|
+
/** @internal */
|
|
84
203
|
onFocus() {
|
|
85
204
|
require_notifyManager.notifyManager.batch(() => {
|
|
86
205
|
this.getAll().forEach((query) => {
|
|
@@ -88,6 +207,7 @@ var QueryCache = class extends require_subscribable.Subscribable {
|
|
|
88
207
|
});
|
|
89
208
|
});
|
|
90
209
|
}
|
|
210
|
+
/** @internal */
|
|
91
211
|
onOnline() {
|
|
92
212
|
require_notifyManager.notifyManager.batch(() => {
|
|
93
213
|
this.getAll().forEach((query) => {
|