@hyper-fetch/react 9.6.1 → 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.
Files changed (91) hide show
  1. package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
  2. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
  3. package/__tests__/features/helpers/utils.spec.ts +127 -0
  4. package/__tests__/features/provider/provider.config.spec.tsx +172 -0
  5. package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
  6. package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
  7. package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
  8. package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
  9. package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
  10. package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
  11. package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
  12. package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
  13. package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
  14. package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
  15. package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
  16. package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
  17. package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
  18. package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
  19. package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
  20. package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
  21. package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
  22. package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
  23. package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
  24. package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
  25. package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
  26. package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
  27. package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
  28. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
  29. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
  30. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
  31. package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
  32. package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
  33. package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
  34. package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
  35. package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
  36. package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
  37. package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
  38. package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
  39. package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
  40. package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
  41. package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
  42. package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
  43. package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
  44. package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
  45. package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
  46. package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +6 -0
  47. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  48. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  49. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  50. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  51. package/__tests__/utils/gate.utils.ts +103 -0
  52. package/__tests__/utils/gated-client.utils.ts +158 -0
  53. package/__tests__/utils/helpers.utils.ts +19 -0
  54. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  55. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  56. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  57. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  58. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  59. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  60. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  61. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  62. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  63. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  64. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  65. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  66. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  67. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  68. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  69. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  70. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  71. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  72. package/dist/index.mjs +630 -346
  73. package/dist/index.mjs.map +1 -1
  74. package/dist/provider/provider.d.ts.map +1 -1
  75. package/package.json +1 -1
  76. package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
  77. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  78. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  79. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  80. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  81. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  82. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  83. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  84. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  85. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  86. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  87. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  88. package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
  89. package/src/provider/provider.tsx +9 -1
  90. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  91. 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":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAOzE;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,sBAAsB,aAAa,4CAS3D,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,QAAO,iBAG9B,CAAC"}
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.1",
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,35 +152,79 @@ export const useRequestEvents = <R extends RequestInstance>({
137
152
  return;
138
153
  }
139
154
 
140
- const canDisableLoading = !loading && !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope));
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 = (data: RequestProgressEventType<RequestInstance>) => {
148
- onDownloadProgressCallback.current?.(data);
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 = (data: RequestProgressEventType<RequestInstance>) => {
152
- onUploadProgressCallback.current?.(data);
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
- const data = runResponseMapper(request, values.response);
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 () => {
@@ -177,11 +236,46 @@ export const useRequestEvents = <R extends RequestInstance>({
177
236
  handleResponseCallbacks({ ...values, response });
178
237
  })();
179
238
  }
180
- return handleResponseCallbacks(values);
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
+ });
181
244
  };
182
245
  };
183
246
 
184
- const handleRemove = ({ requestId }: RequestEventType<R>) => {
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);
185
279
  optimisticResultsRef.current.delete(requestId);
186
280
  removeLifecycleListener(requestId);
187
281
  };
@@ -212,6 +306,10 @@ export const useRequestEvents = <R extends RequestInstance>({
212
306
  return;
213
307
  }
214
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
+ }
215
313
  });
216
314
 
217
315
  const unmount = () => {
@@ -221,6 +319,7 @@ export const useRequestEvents = <R extends RequestInstance>({
221
319
 
222
320
  clearCacheDataListener();
223
321
  dataEvents.current = { unmount };
322
+ listenedQueryKey.current = scopeKey(req.queryKey, req.scope);
224
323
 
225
324
  return unmount;
226
325
  };
@@ -243,11 +342,11 @@ export const useRequestEvents = <R extends RequestInstance>({
243
342
  // events to be triggered during lifecycle
244
343
  clearLifecycleListeners();
245
344
  const { queryKey, cacheKey } = req;
246
- const requestStartUnmount = requestManager.events.onRequestStartByQueue(queryKey, handleRequestStart());
247
- const responseStartUnmount = requestManager.events.onResponseStartByQueue(queryKey, handleResponseStart());
248
- const uploadUnmount = requestManager.events.onUploadProgressByQueue(queryKey, handleUploadProgress);
249
- const downloadUnmount = requestManager.events.onDownloadProgressByQueue(queryKey, handleDownloadProgress);
250
- 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));
251
350
 
252
351
  const unmount = () => {
253
352
  downloadUnmount();
@@ -267,12 +366,18 @@ export const useRequestEvents = <R extends RequestInstance>({
267
366
  if (optimisticResult) {
268
367
  optimisticResultsRef.current.set(requestId, optimisticResult);
269
368
  }
369
+ pendingRequests.current.add(requestId);
370
+ const onRequestStart = handleRequestStart(req);
270
371
  const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);
271
- const requestStartUnmount = requestManager.events.onRequestStartById(requestId, handleRequestStart());
272
- const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart());
273
- const responseUnmount = requestManager.events.onResponseById(requestId, handleResponse());
274
- const uploadUnmount = requestManager.events.onUploadProgressById(requestId, handleUploadProgress);
275
- const downloadUnmount = requestManager.events.onDownloadProgressById(requestId, handleDownloadProgress);
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));
276
381
 
277
382
  const unmount = () => {
278
383
  requestRemove();
@@ -293,13 +398,15 @@ export const useRequestEvents = <R extends RequestInstance>({
293
398
  // ******************
294
399
 
295
400
  const abort = () => {
296
- const ak = scopeKey(request.abortKey, request.scope);
297
- const requests = dispatcher.getAllRunningRequests();
401
+ const currentRequest = requestRef.current;
402
+ const currentDispatcher = dispatcherRef.current;
403
+ const ak = scopeKey(currentRequest.abortKey, currentRequest.scope);
404
+ const requests = currentDispatcher.getAllRunningRequests();
298
405
  requests.forEach((requestData) => {
299
406
  const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);
300
407
  if (reqAk === ak) {
301
408
  const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);
302
- dispatcher.delete(qk, requestData.requestId, reqAk);
409
+ currentDispatcher.delete(qk, requestData.requestId, reqAk);
303
410
  }
304
411
  });
305
412
  };
@@ -317,8 +424,10 @@ export const useRequestEvents = <R extends RequestInstance>({
317
424
  clearCacheDataListener();
318
425
  });
319
426
 
320
- return [
321
- {
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 = {
322
431
  abort,
323
432
  onSuccess: (callback: OnSuccessCallbackType<R>) => {
324
433
  onSuccessCallback.current = callback;
@@ -347,7 +456,11 @@ export const useRequestEvents = <R extends RequestInstance>({
347
456
  onUploadProgress: (callback: OnProgressCallbackType) => {
348
457
  onUploadProgressCallback.current = callback;
349
458
  },
350
- },
459
+ };
460
+ }
461
+
462
+ return [
463
+ callbacksRef.current,
351
464
  {
352
465
  addCacheDataListener,
353
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(cacheKey);
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(scopeKey(cacheKey, request.scope));
140
- return !cacheData || isStaleCacheData(staleTime, cacheData?.responseTimestamp);
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) {emitChange();}
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
- const oldKey = previousCacheKey.current;
165
- previousCacheKey.current = cacheKey;
166
-
167
- // Get cache state
168
- const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope));
169
- const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
170
-
171
- // Determine whether to clear state based on keepPreviousData mode
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: scopeKey(request.queryKey, request.scope),
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
- [cacheKey, queryKey],
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(scopeKey(queryKey, request.scope)),
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
- const actions: UseTrackedStateActions<T, TData> = {
331
- setData: (data) => {
332
- isLocalData.current = true;
333
- state.current.data = data instanceof Function ? data(state.current.data || null) : data;
334
- renderKeyTrigger(["data"]);
335
- },
336
- setError: (error) => {
337
- state.current.error = error instanceof Function ? error(state.current.error || null) : error;
338
- renderKeyTrigger(["error"]);
339
- },
340
- setLoading: (loading) => {
341
- const value = loading instanceof Function ? loading(state.current.loading) : loading;
342
- if (value === state.current.loading) {return;}
343
- state.current.loading = value;
344
- renderKeyTrigger(["loading"]);
345
- },
346
- setStatus: (status) => {
347
- const value = status instanceof Function ? status(state.current.status) : status;
348
- if (value === state.current.status) {return;}
349
- state.current.status = status instanceof Function ? status(state.current.status || null) : status;
350
- renderKeyTrigger(["status"]);
351
- },
352
- setSuccess: (success) => {
353
- const value = success instanceof Function ? success(state.current.success || false) : success;
354
- if (value === state.current.success) {return;}
355
- state.current.success = success instanceof Function ? success(state.current.success || false) : success;
356
- renderKeyTrigger(["success"]);
357
- },
358
- setExtra: (extra) => {
359
- const value = extra instanceof Function ? extra(state.current.extra) : extra;
360
- if (value === state.current.extra) {return;}
361
- state.current.extra = extra instanceof Function ? extra(state.current.extra) : extra;
362
- renderKeyTrigger(["extra"]);
363
- },
364
- setRetries: (retries) => {
365
- const value = retries instanceof Function ? retries(state.current.retries || 0) : retries;
366
- if (value === state.current.retries) {return;}
367
- state.current.retries = retries instanceof Function ? retries(state.current.retries || 0) : retries;
368
- renderKeyTrigger(["retries"]);
369
- },
370
- setResponseTimestamp: (timestamp) => {
371
- const value = timestamp instanceof Function ? timestamp(state.current.responseTimestamp) : timestamp;
372
- if (value === state.current.responseTimestamp) {return;}
373
- const getTimestamp = (prev: Date | null) => {
374
- return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
375
- };
376
-
377
- state.current.responseTimestamp = getTimestamp(state.current.responseTimestamp);
378
- renderKeyTrigger(["responseTimestamp"]);
379
- },
380
- setRequestTimestamp: (timestamp) => {
381
- const value = timestamp instanceof Function ? timestamp(state.current.requestTimestamp) : timestamp;
382
- if (value === state.current.requestTimestamp) {return;}
383
- const getTimestamp = (prev: Date | null) => {
384
- return timestamp instanceof Function ? timestamp(prev ? new Date(prev) : null) : timestamp;
385
- };
386
-
387
- state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);
388
- renderKeyTrigger(["requestTimestamp"]);
389
- },
390
- clearState: () => {
391
- rawData.current = null;
392
- isLocalData.current = false;
393
- responseDetails.current = null;
394
- state.current = {
395
- data: null,
396
- error: null,
397
- loading: false,
398
- status: null,
399
- success: false,
400
- extra: null,
401
- retries: 0,
402
- responseTimestamp: null,
403
- requestTimestamp: null,
404
- } as UseTrackedStateType<T, TData>;
405
- renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T, TData>)[]);
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,