@hyper-fetch/react 9.6.0 → 9.6.2
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/__tests__/features/helpers/use-request-events/use-request-events.async-mapper.spec.ts +243 -0
- package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
- package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
- package/__tests__/features/helpers/utils.spec.ts +127 -0
- package/__tests__/features/provider/provider.config.spec.tsx +172 -0
- package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
- package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
- package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
- package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
- package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
- package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
- package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +6 -3
- package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +72 -80
- package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
- package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
- package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
- package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
- package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
- package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
- package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
- package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
- package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +36 -13
- package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
- package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
- package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
- package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
- package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
- package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
- package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
- package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
- package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +11 -2
- package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
- package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +19 -9
- package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
- package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
- package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
- package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
- package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
- package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
- package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
- package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
- package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
- package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
- package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
- package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +2 -1
- package/__tests__/features/use-submit/use-submit.debounce.spec.ts +100 -124
- package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
- package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
- package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
- package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +8 -1
- package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
- package/__tests__/features/use-submit/use-submit.retry.spec.ts +51 -35
- package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
- package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
- package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
- package/__tests__/features/use-submit/use-submit.unmount.spec.ts +2 -1
- package/__tests__/utils/gate.utils.ts +103 -0
- package/__tests__/utils/gated-client.utils.ts +158 -0
- package/__tests__/utils/helpers.utils.ts +19 -0
- package/__tests__/utils/use-queue.utils.ts +8 -4
- package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
- package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
- package/dist/index.mjs +633 -347
- package/dist/index.mjs.map +1 -1
- package/dist/provider/provider.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +147 -32
- package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
- package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
- package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
- package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
- package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
- package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
- package/src/provider/provider.tsx +9 -1
- package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
- package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/provider/provider.tsx"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/provider/provider.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAOzE;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,sBAAsB,aAAa,4CAgB3D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,QAAO,iBAG9B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyper-fetch/react",
|
|
3
|
-
"version": "9.6.
|
|
3
|
+
"version": "9.6.2",
|
|
4
4
|
"description": "React hooks and utils for the hyper-fetch",
|
|
5
5
|
"author": "Maciej Pyrc <maciekpyrc@gmail.com>, Kacper Skawina <kacper.skawina@gmail.com>",
|
|
6
6
|
"homepage": "https://hyperfetch.bettertyped.com/",
|
|
@@ -5,13 +5,14 @@ import type {
|
|
|
5
5
|
RequestInstance,
|
|
6
6
|
RequestEventType,
|
|
7
7
|
RequestLoadingEventType,
|
|
8
|
+
RequestRemovedEventType,
|
|
8
9
|
ExtractAdapterType,
|
|
9
10
|
RequestProgressEventType,
|
|
10
11
|
RequestResponseEventType,
|
|
11
12
|
ResponseType,
|
|
12
13
|
OptimisticCallbackResult,
|
|
13
14
|
} from "@hyper-fetch/core";
|
|
14
|
-
import { runResponseMapper, scopeKey } from "@hyper-fetch/core";
|
|
15
|
+
import { getErrorMessage, runResponseMapper, scopeKey } from "@hyper-fetch/core";
|
|
15
16
|
import type {
|
|
16
17
|
OnErrorCallbackType,
|
|
17
18
|
OnStartCallbackType,
|
|
@@ -42,6 +43,12 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
42
43
|
}: UseRequestEventsPropsType<R>): UseRequestEventsReturnType<R> => {
|
|
43
44
|
const { cache, requestManager } = request.client;
|
|
44
45
|
|
|
46
|
+
// Always points to the request from the latest render - handlers created once can use it safely
|
|
47
|
+
const requestRef = useRef(request);
|
|
48
|
+
requestRef.current = request;
|
|
49
|
+
const dispatcherRef = useRef(dispatcher);
|
|
50
|
+
dispatcherRef.current = dispatcher;
|
|
51
|
+
|
|
45
52
|
// ******************
|
|
46
53
|
// Callbacks
|
|
47
54
|
// ******************
|
|
@@ -78,6 +85,7 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
78
85
|
value.unmount();
|
|
79
86
|
});
|
|
80
87
|
events.clear();
|
|
88
|
+
pendingRequests.current.clear();
|
|
81
89
|
};
|
|
82
90
|
|
|
83
91
|
// ******************
|
|
@@ -86,6 +94,13 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
86
94
|
|
|
87
95
|
// Rollback and invalidation are settled by the core - here we only deliver the context to the callbacks
|
|
88
96
|
const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());
|
|
97
|
+
// Requests which already got their last response - their removal from the queue is only a cleanup
|
|
98
|
+
const settledRequests = useRef(new Set<string>());
|
|
99
|
+
// Requests sent with their ids (useSubmit) which are submitted or in flight. The hook is loading as long as there
|
|
100
|
+
// are any - also between two queued requests and when the requests have different keys.
|
|
101
|
+
const pendingRequests = useRef(new Set<string>());
|
|
102
|
+
// Queue which the loading and data listeners follow - the one of the latest request
|
|
103
|
+
const listenedQueryKey = useRef<string | null>(null);
|
|
89
104
|
|
|
90
105
|
// ******************
|
|
91
106
|
// Response handlers
|
|
@@ -137,49 +152,130 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
137
152
|
return;
|
|
138
153
|
}
|
|
139
154
|
|
|
140
|
-
const canDisableLoading =
|
|
155
|
+
const canDisableLoading =
|
|
156
|
+
!loading &&
|
|
157
|
+
!dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope)) &&
|
|
158
|
+
pendingRequests.current.size === 0;
|
|
141
159
|
if (loading || canDisableLoading) {
|
|
142
160
|
actions.setLoading(loading);
|
|
143
161
|
}
|
|
144
162
|
};
|
|
145
163
|
};
|
|
146
164
|
|
|
147
|
-
const handleDownloadProgress = (
|
|
148
|
-
|
|
165
|
+
const handleDownloadProgress = (req: R) => {
|
|
166
|
+
return (data: RequestProgressEventType<RequestInstance>) => {
|
|
167
|
+
if (!isSameScope(data.request?.scope, req.scope)) {
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
onDownloadProgressCallback.current?.(data);
|
|
171
|
+
};
|
|
149
172
|
};
|
|
150
173
|
|
|
151
|
-
const handleUploadProgress = (
|
|
152
|
-
|
|
174
|
+
const handleUploadProgress = (req: R) => {
|
|
175
|
+
return (data: RequestProgressEventType<RequestInstance>) => {
|
|
176
|
+
if (!isSameScope(data.request?.scope, req.scope)) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
onUploadProgressCallback.current?.(data);
|
|
180
|
+
};
|
|
153
181
|
};
|
|
154
182
|
|
|
155
|
-
const handleRequestStart = () => {
|
|
183
|
+
const handleRequestStart = (req: R) => {
|
|
156
184
|
return (details: RequestEventType<R>) => {
|
|
185
|
+
if (!isSameScope(details.request?.scope, req.scope)) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
157
188
|
onRequestStartCallback.current?.(details);
|
|
158
189
|
};
|
|
159
190
|
};
|
|
160
|
-
const handleResponseStart = () => {
|
|
191
|
+
const handleResponseStart = (req: R) => {
|
|
161
192
|
return (details: RequestEventType<R>) => {
|
|
193
|
+
if (!isSameScope(details.request?.scope, req.scope)) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
162
196
|
onResponseStartCallback.current?.(details);
|
|
163
197
|
};
|
|
164
198
|
};
|
|
165
199
|
|
|
166
|
-
const handleResponse = () => {
|
|
200
|
+
const handleResponse = (req: R) => {
|
|
167
201
|
return (values: RequestResponseEventType<R>) => {
|
|
168
|
-
|
|
202
|
+
if (!isSameScope(values.request?.scope, req.scope)) {
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// This attempt is over - a retried request becomes pending again when its next attempt starts
|
|
207
|
+
pendingRequests.current.delete(values.requestId);
|
|
208
|
+
|
|
209
|
+
// Marked before the mapper runs - an async mapper answers after the dispatcher removed the request.
|
|
210
|
+
// Failed attempts which are retried or kept for the connection to return respond once again.
|
|
211
|
+
const { success } = values.response;
|
|
212
|
+
const { isCanceled, isOffline, willRetry } = values.details;
|
|
213
|
+
const willRespondAgain = !success && !isCanceled && (willRetry || (!!req.offline && isOffline));
|
|
214
|
+
if (!willRespondAgain) {
|
|
215
|
+
settledRequests.current.add(values.requestId);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// The loading listeners follow the queue of the latest request. A request sent earlier to another queue
|
|
219
|
+
// (other params) is not heard by them, so when it is the last one, it ends the loading state here.
|
|
220
|
+
const queryKey = scopeKey(req.queryKey, req.scope);
|
|
221
|
+
const isLastRequest = pendingRequests.current.size === 0 && !dispatcher.hasRunningRequests(queryKey);
|
|
222
|
+
if (isLastRequest && listenedQueryKey.current !== null && listenedQueryKey.current !== queryKey) {
|
|
223
|
+
actions.setLoading(dispatcher.hasRunningRequests(listenedQueryKey.current));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// The mapper of the listened request - it can differ from the request of the current render
|
|
227
|
+
const data = runResponseMapper(req, values.response);
|
|
169
228
|
|
|
170
229
|
if (data instanceof Promise) {
|
|
171
230
|
return (async () => {
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
231
|
+
const response = (await data) as ResponseType<any, any, ExtractAdapterType<R>>;
|
|
232
|
+
// The mapper can outlive the component - the unmount cleanup can't stop a response already being mapped
|
|
233
|
+
if (!isMounted.current) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
handleResponseCallbacks({ ...values, response });
|
|
176
237
|
})();
|
|
177
238
|
}
|
|
178
|
-
|
|
239
|
+
// Callbacks receive the same (mapped) response as the hook state
|
|
240
|
+
return handleResponseCallbacks({
|
|
241
|
+
...values,
|
|
242
|
+
response: (data || values.response) as ResponseType<any, any, ExtractAdapterType<R>>,
|
|
243
|
+
});
|
|
179
244
|
};
|
|
180
245
|
};
|
|
181
246
|
|
|
182
|
-
const handleRemove = ({ requestId }:
|
|
247
|
+
const handleRemove = ({ requestId, request: removedRequest }: RequestRemovedEventType<R>) => {
|
|
248
|
+
// Removed before its last response - aborted with the hook, deleted or cleared from the queue. No response is
|
|
249
|
+
// going to reach the listeners anymore, so the removal is what ends the request: the abort callback runs with
|
|
250
|
+
// the same "deleted" response that `submit()` resolves with.
|
|
251
|
+
if (!settledRequests.current.has(requestId) && lifecycleEvents.current.has(requestId)) {
|
|
252
|
+
const timestamp = Date.now();
|
|
253
|
+
handleResponseCallbacks({
|
|
254
|
+
request: removedRequest,
|
|
255
|
+
requestId,
|
|
256
|
+
response: {
|
|
257
|
+
data: null,
|
|
258
|
+
error: getErrorMessage("deleted") as ExtractErrorType<R>,
|
|
259
|
+
status: null,
|
|
260
|
+
success: false,
|
|
261
|
+
extra: removedRequest.client.adapter.defaultExtra,
|
|
262
|
+
requestTimestamp: timestamp,
|
|
263
|
+
responseTimestamp: timestamp,
|
|
264
|
+
},
|
|
265
|
+
details: {
|
|
266
|
+
retries: 0,
|
|
267
|
+
isCanceled: true,
|
|
268
|
+
isOffline: false,
|
|
269
|
+
willRetry: false,
|
|
270
|
+
addedTimestamp: timestamp,
|
|
271
|
+
triggerTimestamp: timestamp,
|
|
272
|
+
requestTimestamp: timestamp,
|
|
273
|
+
responseTimestamp: timestamp,
|
|
274
|
+
},
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
settledRequests.current.delete(requestId);
|
|
278
|
+
pendingRequests.current.delete(requestId);
|
|
183
279
|
optimisticResultsRef.current.delete(requestId);
|
|
184
280
|
removeLifecycleListener(requestId);
|
|
185
281
|
};
|
|
@@ -210,6 +306,10 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
210
306
|
return;
|
|
211
307
|
}
|
|
212
308
|
setCacheData(cacheData);
|
|
309
|
+
// Cache data brings the loading state of its own queue only - other requests of the hook can still be pending
|
|
310
|
+
if (pendingRequests.current.size > 0) {
|
|
311
|
+
actions.setLoading(true);
|
|
312
|
+
}
|
|
213
313
|
});
|
|
214
314
|
|
|
215
315
|
const unmount = () => {
|
|
@@ -219,6 +319,7 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
219
319
|
|
|
220
320
|
clearCacheDataListener();
|
|
221
321
|
dataEvents.current = { unmount };
|
|
322
|
+
listenedQueryKey.current = scopeKey(req.queryKey, req.scope);
|
|
222
323
|
|
|
223
324
|
return unmount;
|
|
224
325
|
};
|
|
@@ -241,11 +342,11 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
241
342
|
// events to be triggered during lifecycle
|
|
242
343
|
clearLifecycleListeners();
|
|
243
344
|
const { queryKey, cacheKey } = req;
|
|
244
|
-
const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart());
|
|
245
|
-
const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart());
|
|
246
|
-
const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress);
|
|
247
|
-
const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress);
|
|
248
|
-
const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse());
|
|
345
|
+
const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart(req));
|
|
346
|
+
const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart(req));
|
|
347
|
+
const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress(req));
|
|
348
|
+
const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress(req));
|
|
349
|
+
const responseUnmount = requestManager.events.onResponseByCache(cacheKey, handleResponse(req));
|
|
249
350
|
|
|
250
351
|
const unmount = () => {
|
|
251
352
|
downloadUnmount();
|
|
@@ -265,12 +366,18 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
265
366
|
if (optimisticResult) {
|
|
266
367
|
optimisticResultsRef.current.set(requestId, optimisticResult);
|
|
267
368
|
}
|
|
369
|
+
pendingRequests.current.add(requestId);
|
|
370
|
+
const onRequestStart = handleRequestStart(req);
|
|
268
371
|
const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);
|
|
269
|
-
const requestStartUnmount = requestManager.events.onRequestStartById(requestId,
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
372
|
+
const requestStartUnmount = requestManager.events.onRequestStartById<R>(requestId, (details) => {
|
|
373
|
+
// Every attempt, also a retry or one postponed until the connection returned
|
|
374
|
+
pendingRequests.current.add(requestId);
|
|
375
|
+
onRequestStart(details);
|
|
376
|
+
});
|
|
377
|
+
const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart(req));
|
|
378
|
+
const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse(req));
|
|
379
|
+
const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress(req));
|
|
380
|
+
const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress(req));
|
|
274
381
|
|
|
275
382
|
const unmount = () => {
|
|
276
383
|
requestRemove();
|
|
@@ -291,13 +398,15 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
291
398
|
// ******************
|
|
292
399
|
|
|
293
400
|
const abort = () => {
|
|
294
|
-
const
|
|
295
|
-
const
|
|
401
|
+
const currentRequest = requestRef.current;
|
|
402
|
+
const currentDispatcher = dispatcherRef.current;
|
|
403
|
+
const ak = scopeKey(currentRequest.abortKey, currentRequest.scope);
|
|
404
|
+
const requests = currentDispatcher.getAllRunningRequests();
|
|
296
405
|
requests.forEach((requestData) => {
|
|
297
406
|
const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);
|
|
298
407
|
if (reqAk === ak) {
|
|
299
408
|
const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);
|
|
300
|
-
|
|
409
|
+
currentDispatcher.delete(qk, requestData.requestId, reqAk);
|
|
301
410
|
}
|
|
302
411
|
});
|
|
303
412
|
};
|
|
@@ -315,8 +424,10 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
315
424
|
clearCacheDataListener();
|
|
316
425
|
});
|
|
317
426
|
|
|
318
|
-
|
|
319
|
-
|
|
427
|
+
// Callbacks setters and abort work on refs only, so they are created once - their identity is stable between the renders
|
|
428
|
+
const callbacksRef = useRef<UseRequestEventsReturnType<R>[0] | null>(null);
|
|
429
|
+
if (!callbacksRef.current) {
|
|
430
|
+
callbacksRef.current = {
|
|
320
431
|
abort,
|
|
321
432
|
onSuccess: (callback: OnSuccessCallbackType<R>) => {
|
|
322
433
|
onSuccessCallback.current = callback;
|
|
@@ -345,7 +456,11 @@ export const useRequestEvents = <R extends RequestInstance>({
|
|
|
345
456
|
onUploadProgress: (callback: OnProgressCallbackType) => {
|
|
346
457
|
onUploadProgressCallback.current = callback;
|
|
347
458
|
},
|
|
348
|
-
}
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return [
|
|
463
|
+
callbacksRef.current,
|
|
349
464
|
{
|
|
350
465
|
addCacheDataListener,
|
|
351
466
|
clearCacheDataListener,
|
|
@@ -95,7 +95,7 @@ export type UseRequestEventsReturnType<T extends RequestInstance> = [
|
|
|
95
95
|
export type CallbackParameters<Request extends RequestInstance, Resp> = {
|
|
96
96
|
response: Resp;
|
|
97
97
|
mutationContext: ExtractMutationContextType<Request> | undefined;
|
|
98
|
-
} & Omit<RequestResponseEventType<Request>, "response">;
|
|
98
|
+
} & Omit<RequestResponseEventType<Request>, "response" | "mutationContext">;
|
|
99
99
|
|
|
100
100
|
export type OnSuccessCallbackType<Request extends RequestInstance> = (
|
|
101
101
|
params: CallbackParameters<Request, ResponseSuccessType<ExtractResponseType<Request>, ExtractAdapterType<Request>>>,
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
import {
|
|
25
25
|
getInitialState,
|
|
26
26
|
getIsInitiallyLoading,
|
|
27
|
+
getRequestIdentity,
|
|
27
28
|
getShouldClearState,
|
|
28
29
|
getValidCacheData,
|
|
29
30
|
isStaleCacheData,
|
|
@@ -51,12 +52,19 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
51
52
|
}: UseTrackedStateProps<T, TData>): UseTrackedStateReturn<T, TData> => {
|
|
52
53
|
const { client, cacheKey, queryKey, staleTime } = request;
|
|
53
54
|
const { cache } = client;
|
|
55
|
+
// Cache storage and dispatcher queues are keyed with the scope of the request
|
|
56
|
+
const scopedCacheKey = scopeKey(cacheKey, request.scope);
|
|
57
|
+
const scopedQueryKey = scopeKey(queryKey, request.scope);
|
|
58
|
+
const identity = getRequestIdentity(request);
|
|
54
59
|
const hydration = useHydration();
|
|
55
60
|
|
|
56
61
|
const state = useRef<UseTrackedStateType<T, TData>>(null as unknown as UseTrackedStateType<T, TData>);
|
|
57
62
|
const renderKeys = useRef<(keyof UseTrackedStateType<T, TData>)[]>([]);
|
|
58
63
|
const isProcessingData = useRef("");
|
|
59
|
-
const previousCacheKey = useRef(
|
|
64
|
+
const previousCacheKey = useRef(scopedCacheKey);
|
|
65
|
+
const previousIdentity = useRef(identity);
|
|
66
|
+
// State created from scratch can be filled with the initialResponse, the preserved one (keepPreviousData) can not
|
|
67
|
+
const isFreshState = useRef(true);
|
|
60
68
|
|
|
61
69
|
// ******************
|
|
62
70
|
// Data selection
|
|
@@ -94,6 +102,29 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
94
102
|
getInitialState({ initialResponse, dispatcher, request, disabled, hydratedEntry }),
|
|
95
103
|
);
|
|
96
104
|
}
|
|
105
|
+
// Request key changed - the state is switched during the render, so the data of the previous key
|
|
106
|
+
// is never returned for the new one (unless it is kept on purpose with keepPreviousData)
|
|
107
|
+
else if (previousCacheKey.current !== scopedCacheKey) {
|
|
108
|
+
// "auto" mode keeps the state of the same resource (only its query params changed).
|
|
109
|
+
// Resources are compared by the requests, cache keys can't be parsed reliably.
|
|
110
|
+
const shouldClear =
|
|
111
|
+
keepPreviousData === "auto"
|
|
112
|
+
? previousIdentity.current !== identity
|
|
113
|
+
: getShouldClearState(keepPreviousData, previousCacheKey.current, scopedCacheKey);
|
|
114
|
+
previousCacheKey.current = scopedCacheKey;
|
|
115
|
+
previousIdentity.current = identity;
|
|
116
|
+
|
|
117
|
+
const hasCacheData = !!cache.get(scopedCacheKey);
|
|
118
|
+
isFreshState.current = hasCacheData || shouldClear;
|
|
119
|
+
|
|
120
|
+
if (isFreshState.current) {
|
|
121
|
+
const hydratedEntry = hydration?.get(client, scopedCacheKey);
|
|
122
|
+
state.current = getSelectedState(
|
|
123
|
+
getInitialState({ initialResponse, dispatcher, request, disabled, revalidate, hydratedEntry }),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
// Otherwise the previous state stays until the response of the new key arrives (#126)
|
|
127
|
+
}
|
|
97
128
|
|
|
98
129
|
// Selector failed while processing incoming data - surface it to the closest error boundary
|
|
99
130
|
if (selectError.current) {
|
|
@@ -136,8 +167,11 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
136
167
|
// ******************
|
|
137
168
|
|
|
138
169
|
const getStaleStatus = (): boolean => {
|
|
139
|
-
const cacheData = cache.get(
|
|
140
|
-
|
|
170
|
+
const cacheData = cache.get(scopedCacheKey);
|
|
171
|
+
// Invalidation marks the cache entry with the stale time of 0 - it has to be fetched again,
|
|
172
|
+
// also when no hook was mounted to refetch it at the moment of the invalidation
|
|
173
|
+
const isInvalidated = cacheData?.staleTime === 0;
|
|
174
|
+
return !cacheData || isInvalidated || isStaleCacheData(staleTime, cacheData?.responseTimestamp);
|
|
141
175
|
};
|
|
142
176
|
|
|
143
177
|
// ******************
|
|
@@ -146,7 +180,9 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
146
180
|
|
|
147
181
|
const renderKeyTrigger = (keys: (keyof UseTrackedStateType<T, TData>)[]) => {
|
|
148
182
|
const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
|
|
149
|
-
if (shouldRerender) {
|
|
183
|
+
if (shouldRerender) {
|
|
184
|
+
emitChange();
|
|
185
|
+
}
|
|
150
186
|
};
|
|
151
187
|
|
|
152
188
|
const setRenderKey = (renderKey: keyof UseTrackedStateType<T, TData>) => {
|
|
@@ -161,24 +197,16 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
161
197
|
|
|
162
198
|
useDidUpdate(
|
|
163
199
|
() => {
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
//
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const shouldClear = getShouldClearState(keepPreviousData, oldKey, cacheKey);
|
|
173
|
-
|
|
174
|
-
if (shouldClear && !cacheState) {
|
|
175
|
-
// Reset state to initial values when no cached data exists for the new key
|
|
176
|
-
const resetState = getInitialState({ initialResponse, dispatcher, request, disabled, revalidate });
|
|
177
|
-
state.current = getSelectedState(resetState);
|
|
178
|
-
renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);
|
|
179
|
-
} else if (cacheState) {
|
|
200
|
+
// The state of the key is already set during the render. Here we pick up the changes done to the cache
|
|
201
|
+
// between the render and the effect and the data that requires asynchronous mapping.
|
|
202
|
+
const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopedCacheKey);
|
|
203
|
+
// Initial response is a placeholder for the empty state only - it never replaces the data kept from the previous key
|
|
204
|
+
const cacheState =
|
|
205
|
+
cacheData || (isFreshState.current ? getValidCacheData<T>(request, initialResponse, null) : null);
|
|
206
|
+
|
|
207
|
+
if (cacheState) {
|
|
180
208
|
state.current.loading = getIsInitiallyLoading({
|
|
181
|
-
queryKey:
|
|
209
|
+
queryKey: scopedQueryKey,
|
|
182
210
|
dispatcher,
|
|
183
211
|
disabled,
|
|
184
212
|
revalidate,
|
|
@@ -190,7 +218,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
190
218
|
// When state is preserved and no cache exists (e.g. query param change in "auto" mode),
|
|
191
219
|
// don't update loading on the ref — let the dispatcher's loading event handle it (#126)
|
|
192
220
|
},
|
|
193
|
-
[
|
|
221
|
+
[scopedCacheKey, scopedQueryKey],
|
|
194
222
|
true,
|
|
195
223
|
);
|
|
196
224
|
|
|
@@ -260,7 +288,7 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
260
288
|
retries: cacheData.retries,
|
|
261
289
|
responseTimestamp: new Date(cacheData.responseTimestamp),
|
|
262
290
|
requestTimestamp: new Date(cacheData.requestTimestamp),
|
|
263
|
-
loading: dispatcher.hasRunningRequests(
|
|
291
|
+
loading: dispatcher.hasRunningRequests(scopedQueryKey),
|
|
264
292
|
};
|
|
265
293
|
|
|
266
294
|
const nextState: UseTrackedStateType<T, TData> = { ...state.current };
|
|
@@ -327,84 +355,103 @@ export const useTrackedState = <T extends RequestInstance, TData = ExtractRespon
|
|
|
327
355
|
// Actions
|
|
328
356
|
// ******************
|
|
329
357
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
358
|
+
// Actions work on refs only, so they are created once - their identity is stable between the renders
|
|
359
|
+
const actionsRef = useRef<UseTrackedStateActions<T, TData> | null>(null);
|
|
360
|
+
if (!actionsRef.current) {
|
|
361
|
+
actionsRef.current = {
|
|
362
|
+
setData: (data) => {
|
|
363
|
+
isLocalData.current = true;
|
|
364
|
+
state.current.data = data instanceof Function ? data(state.current.data ?? null) : data;
|
|
365
|
+
renderKeyTrigger(["data"]);
|
|
366
|
+
},
|
|
367
|
+
setError: (error) => {
|
|
368
|
+
state.current.error = error instanceof Function ? error(state.current.error ?? null) : error;
|
|
369
|
+
renderKeyTrigger(["error"]);
|
|
370
|
+
},
|
|
371
|
+
setLoading: (loading) => {
|
|
372
|
+
const value = loading instanceof Function ? loading(state.current.loading) : loading;
|
|
373
|
+
if (value === state.current.loading) {
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
state.current.loading = value;
|
|
377
|
+
renderKeyTrigger(["loading"]);
|
|
378
|
+
},
|
|
379
|
+
setStatus: (status) => {
|
|
380
|
+
const value = status instanceof Function ? status(state.current.status ?? null) : status;
|
|
381
|
+
if (value === state.current.status) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
state.current.status = value;
|
|
385
|
+
renderKeyTrigger(["status"]);
|
|
386
|
+
},
|
|
387
|
+
setSuccess: (success) => {
|
|
388
|
+
const value = success instanceof Function ? success(state.current.success || false) : success;
|
|
389
|
+
if (value === state.current.success) {
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
state.current.success = value;
|
|
393
|
+
renderKeyTrigger(["success"]);
|
|
394
|
+
},
|
|
395
|
+
setExtra: (extra) => {
|
|
396
|
+
const value = extra instanceof Function ? extra(state.current.extra) : extra;
|
|
397
|
+
if (value === state.current.extra) {
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
state.current.extra = value;
|
|
401
|
+
renderKeyTrigger(["extra"]);
|
|
402
|
+
},
|
|
403
|
+
setRetries: (retries) => {
|
|
404
|
+
const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;
|
|
405
|
+
if (value === state.current.retries) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
state.current.retries = value;
|
|
409
|
+
renderKeyTrigger(["retries"]);
|
|
410
|
+
},
|
|
411
|
+
setResponseTimestamp: (timestamp) => {
|
|
412
|
+
const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;
|
|
413
|
+
if (value === state.current.responseTimestamp) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const getTimestamp = (prev: Date | null) => {
|
|
417
|
+
return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);
|
|
421
|
+
renderKeyTrigger(["responseTimestamp"]);
|
|
422
|
+
},
|
|
423
|
+
setRequestTimestamp: (timestamp) => {
|
|
424
|
+
const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;
|
|
425
|
+
if (value === state.current.requestTimestamp) {
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const getTimestamp = (prev: Date | null) => {
|
|
429
|
+
return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);
|
|
433
|
+
renderKeyTrigger(["requestTimestamp"]);
|
|
434
|
+
},
|
|
435
|
+
clearState: () => {
|
|
436
|
+
rawData.current = null;
|
|
437
|
+
isLocalData.current = false;
|
|
438
|
+
responseDetails.current = null;
|
|
439
|
+
state.current = {
|
|
440
|
+
data: null,
|
|
441
|
+
error: null,
|
|
442
|
+
loading: false,
|
|
443
|
+
status: null,
|
|
444
|
+
success: false,
|
|
445
|
+
extra: client.adapter.defaultExtra,
|
|
446
|
+
retries: 0,
|
|
447
|
+
responseTimestamp: null,
|
|
448
|
+
requestTimestamp: null,
|
|
449
|
+
} as UseTrackedStateType<T, TData>;
|
|
450
|
+
renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);
|
|
451
|
+
},
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
const actions = actionsRef.current;
|
|
408
455
|
|
|
409
456
|
return [
|
|
410
457
|
state.current,
|