@hyper-fetch/react 7.5.2 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/.eslintrc.cjs +12 -0
  2. package/__tests__/features/helpers/use-request-events/use-request-events.base.spec.ts +115 -0
  3. package/__tests__/features/helpers/use-request-events/use-request-events.utils.spec.ts +69 -0
  4. package/__tests__/features/helpers/use-socket-state/use-socket-state.base.spec.ts +213 -0
  5. package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +550 -0
  6. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.base.spec.ts +566 -0
  7. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.utils.spec.ts +260 -0
  8. package/__tests__/features/provider/provider.hydration.spec.tsx +165 -0
  9. package/__tests__/features/provider/use-config-provider.base.spec.tsx +69 -0
  10. package/__tests__/features/use-app-manager/use-app-manager.base.spec.ts +85 -0
  11. package/__tests__/features/use-cache/use-cache.base.spec.ts +136 -0
  12. package/__tests__/features/use-cache/use-cache.helpers.ts +40 -0
  13. package/__tests__/features/use-cache/use-cache.typescript.spec.ts +111 -0
  14. package/__tests__/features/use-emitter/use-emitter.base.spec.ts +124 -0
  15. package/__tests__/features/use-fetch/use-fetch.base.spec.ts +372 -0
  16. package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +83 -0
  17. package/__tests__/features/use-fetch/use-fetch.clear-state.spec.ts +82 -0
  18. package/__tests__/features/use-fetch/use-fetch.concurrency.spec.ts +91 -0
  19. package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +153 -0
  20. package/__tests__/features/use-fetch/use-fetch.deduplication.spec.ts +80 -0
  21. package/__tests__/features/use-fetch/use-fetch.infinite.ts +39 -0
  22. package/__tests__/features/use-fetch/use-fetch.integration.spec.tsx +172 -0
  23. package/__tests__/features/use-fetch/use-fetch.keep-previous-data.spec.ts +215 -0
  24. package/__tests__/features/use-fetch/use-fetch.methods.spec.ts +233 -0
  25. package/__tests__/features/use-fetch/use-fetch.offline.spec.ts +103 -0
  26. package/__tests__/features/use-fetch/use-fetch.pagination.ts +36 -0
  27. package/__tests__/features/use-fetch/use-fetch.prefetch.spec.tsx +73 -0
  28. package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +187 -0
  29. package/__tests__/features/use-fetch/use-fetch.rerender.spec.tsx +151 -0
  30. package/__tests__/features/use-fetch/use-fetch.retry.ts +38 -0
  31. package/__tests__/features/use-fetch/use-fetch.revalidate.spec.ts +237 -0
  32. package/__tests__/features/use-fetch/use-fetch.suspense.spec.tsx +505 -0
  33. package/__tests__/features/use-fetch/use-fetch.typescript.spec.ts +182 -0
  34. package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +26 -0
  35. package/__tests__/features/use-fetch/use-fetch.window.spec.ts +131 -0
  36. package/__tests__/features/use-listener/use-listener.base.spec.ts +57 -0
  37. package/__tests__/features/use-queue/use-queue.actions.spec.ts +238 -0
  38. package/__tests__/features/use-queue/use-queue.base.spec.ts +367 -0
  39. package/__tests__/features/use-queue/use-queue.resolve.spec.ts +173 -0
  40. package/__tests__/features/use-stream/use-stream.base.spec.ts +481 -0
  41. package/__tests__/features/use-submit/use-submit.base.spec.ts +76 -0
  42. package/__tests__/features/use-submit/use-submit.cancel.spec.ts +46 -0
  43. package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +62 -0
  44. package/__tests__/features/use-submit/use-submit.debounce.spec.ts +320 -0
  45. package/__tests__/features/use-submit/use-submit.methods.spec.ts +276 -0
  46. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +548 -0
  47. package/__tests__/features/use-submit/use-submit.queue.spec.ts +84 -0
  48. package/__tests__/features/use-submit/use-submit.retry.spec.ts +92 -0
  49. package/__tests__/features/use-submit/use-submit.revalidate.spec.ts +99 -0
  50. package/__tests__/features/use-submit/use-submit.submit.spec.ts +234 -0
  51. package/__tests__/features/use-submit/use-submit.typescript.spec.ts +325 -0
  52. package/__tests__/shared/index.ts +2 -0
  53. package/__tests__/shared/isolation.tests.ts +12 -0
  54. package/__tests__/shared/response.tests.ts +128 -0
  55. package/__tests__/tsconfig.json +27 -0
  56. package/__tests__/utils/cache.utils.ts +55 -0
  57. package/__tests__/utils/client.utils.ts +3 -0
  58. package/__tests__/utils/emitter.utils.ts +8 -0
  59. package/__tests__/utils/helpers.utils.ts +9 -0
  60. package/__tests__/utils/index.ts +14 -0
  61. package/__tests__/utils/listener.utils.ts +11 -0
  62. package/__tests__/utils/request.utils.ts +12 -0
  63. package/__tests__/utils/state.utils.ts +7 -0
  64. package/__tests__/utils/use-app-manager.utils.ts +10 -0
  65. package/__tests__/utils/use-cache.utils.ts +12 -0
  66. package/__tests__/utils/use-emitter.utils.ts +12 -0
  67. package/__tests__/utils/use-fetch.utils.ts +12 -0
  68. package/__tests__/utils/use-listener.utils.ts +12 -0
  69. package/__tests__/utils/use-queue.utils.ts +70 -0
  70. package/__tests__/utils/use-request-events.utils.ts +43 -0
  71. package/__tests__/utils/use-socket-state.utils.ts +12 -0
  72. package/__tests__/utils/use-submit.utils.ts +12 -0
  73. package/__tests__/utils/use-tracked-state.utils.ts +27 -0
  74. package/__tests__/vitest.setup.ts +8 -0
  75. package/dist/helpers/index.d.ts +4 -0
  76. package/dist/helpers/index.d.ts.map +1 -0
  77. package/dist/helpers/use-request-events/index.d.ts +3 -0
  78. package/dist/helpers/use-request-events/index.d.ts.map +1 -0
  79. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts +10 -0
  80. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -0
  81. package/dist/helpers/use-request-events/use-request-events.types.d.ts +78 -0
  82. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -0
  83. package/dist/helpers/use-socket-state/index.d.ts +4 -0
  84. package/dist/helpers/use-socket-state/index.d.ts.map +1 -0
  85. package/dist/helpers/use-socket-state/use-socket-state.constants.d.ts +4 -0
  86. package/dist/helpers/use-socket-state/use-socket-state.constants.d.ts.map +1 -0
  87. package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts +24 -0
  88. package/dist/helpers/use-socket-state/use-socket-state.hooks.d.ts.map +1 -0
  89. package/dist/helpers/use-socket-state/use-socket-state.types.d.ts +12 -0
  90. package/dist/helpers/use-socket-state/use-socket-state.types.d.ts.map +1 -0
  91. package/dist/helpers/use-tracked-state/index.d.ts +5 -0
  92. package/dist/helpers/use-tracked-state/index.d.ts.map +1 -0
  93. package/dist/helpers/use-tracked-state/use-tracked-state.constants.d.ts +3 -0
  94. package/dist/helpers/use-tracked-state/use-tracked-state.constants.d.ts.map +1 -0
  95. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts +12 -0
  96. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -0
  97. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts +113 -0
  98. package/dist/helpers/use-tracked-state/use-tracked-state.types.d.ts.map +1 -0
  99. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +29 -0
  100. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -0
  101. package/dist/hooks/use-app-manager/index.d.ts +3 -0
  102. package/dist/hooks/use-app-manager/index.d.ts.map +1 -0
  103. package/dist/hooks/use-app-manager/use-app-manager.hooks.d.ts +4 -0
  104. package/dist/hooks/use-app-manager/use-app-manager.hooks.d.ts.map +1 -0
  105. package/dist/hooks/use-app-manager/use-app-manager.types.d.ts +19 -0
  106. package/dist/hooks/use-app-manager/use-app-manager.types.d.ts.map +1 -0
  107. package/dist/hooks/use-cache/index.d.ts +4 -0
  108. package/dist/hooks/use-cache/index.d.ts.map +1 -0
  109. package/dist/hooks/use-cache/use-cache.constants.d.ts +6 -0
  110. package/dist/hooks/use-cache/use-cache.constants.d.ts.map +1 -0
  111. package/dist/hooks/use-cache/use-cache.hooks.d.ts +4 -0
  112. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -0
  113. package/dist/hooks/use-cache/use-cache.types.d.ts +24 -0
  114. package/dist/hooks/use-cache/use-cache.types.d.ts.map +1 -0
  115. package/dist/hooks/use-emitter/index.d.ts +3 -0
  116. package/dist/hooks/use-emitter/index.d.ts.map +1 -0
  117. package/dist/hooks/use-emitter/use-emitter.hooks.d.ts +26 -0
  118. package/dist/hooks/use-emitter/use-emitter.hooks.d.ts.map +1 -0
  119. package/dist/hooks/use-emitter/use-emitter.types.d.ts +4 -0
  120. package/dist/hooks/use-emitter/use-emitter.types.d.ts.map +1 -0
  121. package/dist/hooks/use-fetch/index.d.ts +5 -0
  122. package/dist/hooks/use-fetch/index.d.ts.map +1 -0
  123. package/dist/hooks/use-fetch/use-fetch.constants.d.ts +8 -0
  124. package/dist/hooks/use-fetch/use-fetch.constants.d.ts.map +1 -0
  125. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts +10 -0
  126. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -0
  127. package/dist/hooks/use-fetch/use-fetch.types.d.ts +118 -0
  128. package/dist/hooks/use-fetch/use-fetch.types.d.ts.map +1 -0
  129. package/dist/hooks/use-fetch/use-fetch.utils.d.ts +2 -0
  130. package/dist/hooks/use-fetch/use-fetch.utils.d.ts.map +1 -0
  131. package/dist/hooks/use-listener/index.d.ts +3 -0
  132. package/dist/hooks/use-listener/index.d.ts.map +1 -0
  133. package/dist/hooks/use-listener/use-listener.hooks.d.ts +31 -0
  134. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -0
  135. package/dist/hooks/use-listener/use-listener.types.d.ts +4 -0
  136. package/dist/hooks/use-listener/use-listener.types.d.ts.map +1 -0
  137. package/dist/hooks/use-queue/index.d.ts +4 -0
  138. package/dist/hooks/use-queue/index.d.ts.map +1 -0
  139. package/dist/hooks/use-queue/use-queue.constants.d.ts +4 -0
  140. package/dist/hooks/use-queue/use-queue.constants.d.ts.map +1 -0
  141. package/dist/hooks/use-queue/use-queue.hooks.d.ts +10 -0
  142. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -0
  143. package/dist/hooks/use-queue/use-queue.types.d.ts +58 -0
  144. package/dist/hooks/use-queue/use-queue.types.d.ts.map +1 -0
  145. package/dist/hooks/use-stream/index.d.ts +3 -0
  146. package/dist/hooks/use-stream/index.d.ts.map +1 -0
  147. package/dist/hooks/use-stream/use-stream.hooks.d.ts +11 -0
  148. package/dist/hooks/use-stream/use-stream.hooks.d.ts.map +1 -0
  149. package/dist/hooks/use-stream/use-stream.types.d.ts +52 -0
  150. package/dist/hooks/use-stream/use-stream.types.d.ts.map +1 -0
  151. package/dist/hooks/use-submit/index.d.ts +4 -0
  152. package/dist/hooks/use-submit/index.d.ts.map +1 -0
  153. package/dist/hooks/use-submit/use-submit.constants.d.ts +8 -0
  154. package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -0
  155. package/dist/hooks/use-submit/use-submit.hooks.d.ts +10 -0
  156. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -0
  157. package/dist/hooks/use-submit/use-submit.types.d.ts +115 -0
  158. package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -0
  159. package/dist/index.d.ts +12 -733
  160. package/dist/index.d.ts.map +1 -0
  161. package/dist/index.mjs +1935 -0
  162. package/dist/index.mjs.map +1 -0
  163. package/dist/provider/index.d.ts +3 -0
  164. package/dist/provider/index.d.ts.map +1 -0
  165. package/dist/provider/provider.d.ts +13 -0
  166. package/dist/provider/provider.d.ts.map +1 -0
  167. package/dist/provider/provider.types.d.ts +31 -0
  168. package/dist/provider/provider.types.d.ts.map +1 -0
  169. package/dist/utils/bounce.utils.d.ts +8 -0
  170. package/dist/utils/bounce.utils.d.ts.map +1 -0
  171. package/dist/utils/deep-equal.utils.d.ts +14 -0
  172. package/dist/utils/deep-equal.utils.d.ts.map +1 -0
  173. package/dist/utils/index.d.ts +4 -0
  174. package/dist/utils/index.d.ts.map +1 -0
  175. package/dist/utils/tracked-proxy.utils.d.ts +7 -0
  176. package/dist/utils/tracked-proxy.utils.d.ts.map +1 -0
  177. package/package.json +21 -13
  178. package/project.json +4 -0
  179. package/src/helpers/use-request-events/use-request-events.hooks.ts +60 -14
  180. package/src/helpers/use-request-events/use-request-events.types.ts +19 -12
  181. package/src/helpers/use-socket-state/use-socket-state.constants.ts +2 -2
  182. package/src/helpers/use-socket-state/use-socket-state.hooks.ts +47 -13
  183. package/src/helpers/use-socket-state/use-socket-state.types.ts +1 -1
  184. package/src/helpers/use-tracked-state/use-tracked-state.constants.ts +1 -1
  185. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +74 -22
  186. package/src/helpers/use-tracked-state/use-tracked-state.types.ts +7 -2
  187. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +39 -4
  188. package/src/hooks/use-app-manager/use-app-manager.hooks.ts +2 -2
  189. package/src/hooks/use-cache/use-cache.hooks.ts +33 -41
  190. package/src/hooks/use-cache/use-cache.types.ts +3 -3
  191. package/src/hooks/use-emitter/use-emitter.hooks.ts +17 -16
  192. package/src/hooks/use-fetch/use-fetch.constants.ts +5 -2
  193. package/src/hooks/use-fetch/use-fetch.hooks.ts +109 -51
  194. package/src/hooks/use-fetch/use-fetch.types.ts +18 -3
  195. package/src/hooks/use-listener/use-listener.hooks.ts +19 -27
  196. package/src/hooks/use-queue/use-queue.constants.ts +2 -2
  197. package/src/hooks/use-queue/use-queue.hooks.ts +25 -6
  198. package/src/hooks/use-queue/use-queue.types.ts +8 -2
  199. package/src/hooks/use-stream/index.ts +2 -0
  200. package/src/hooks/use-stream/use-stream.hooks.ts +164 -0
  201. package/src/hooks/use-stream/use-stream.types.ts +53 -0
  202. package/src/hooks/use-submit/use-submit.constants.ts +2 -2
  203. package/src/hooks/use-submit/use-submit.hooks.ts +43 -48
  204. package/src/hooks/use-submit/use-submit.types.ts +9 -9
  205. package/src/index.ts +1 -0
  206. package/src/provider/provider.tsx +1 -1
  207. package/src/provider/provider.types.ts +8 -8
  208. package/src/utils/index.ts +1 -0
  209. package/src/utils/tracked-proxy.utils.ts +19 -0
  210. package/tsconfig.json +1 -1
  211. package/vite.config.ts +45 -0
  212. package/.eslintrc.json +0 -11
  213. package/dist/index.js +0 -1541
  214. package/dist/index.js.map +0 -7
@@ -1,4 +1,4 @@
1
- import {
1
+ import type {
2
2
  ExtractErrorType,
3
3
  ExtractResponseType,
4
4
  RequestInstance,
@@ -8,11 +8,13 @@ import {
8
8
  RequestProgressEventType,
9
9
  RequestResponseEventType,
10
10
  ResponseType,
11
+ OptimisticCallbackResult,
11
12
  } from "@hyper-fetch/core";
13
+ import { scopeKey } from "@hyper-fetch/core";
12
14
  import { useWillUnmount } from "@better-hooks/lifecycle";
13
15
  import { useRef } from "react";
14
16
 
15
- import {
17
+ import type {
16
18
  OnErrorCallbackType,
17
19
  OnStartCallbackType,
18
20
  OnSuccessCallbackType,
@@ -78,27 +80,54 @@ export const useRequestEvents = <R extends RequestInstance>({
78
80
  events.clear();
79
81
  };
80
82
 
83
+ // ******************
84
+ // Optimistic state
85
+ // ******************
86
+
87
+ const optimisticResultsRef = useRef<Map<string, OptimisticCallbackResult<any>>>(new Map());
88
+
81
89
  // ******************
82
90
  // Response handlers
83
91
  // ******************
84
92
 
85
93
  const handleResponseCallbacks = (values: RequestResponseEventType<R>) => {
86
94
  const { success } = values.response;
87
- const { isOffline, isCanceled } = values.details;
95
+ const { isOffline, isCanceled, willRetry } = values.details;
96
+ const opt = optimisticResultsRef.current.get(values.requestId);
97
+ const paramsWithContext = { ...values, mutationContext: opt?.context } as any;
98
+
88
99
  if (request.offline && isOffline && !success) {
89
100
  logger.debug({ title: "Performing offline error callback", type: "system", extra: values });
90
- onOfflineErrorCallback.current?.(values as any);
101
+ onOfflineErrorCallback.current?.(paramsWithContext);
91
102
  } else if (isCanceled) {
92
103
  logger.debug({ title: "Performing abort callback", type: "system", extra: values });
93
- onAbortCallback.current?.(values as any);
104
+ try {
105
+ opt?.rollback?.();
106
+ } catch {
107
+ // rollback threw — onAbort still fires
108
+ }
109
+ onAbortCallback.current?.(paramsWithContext);
94
110
  } else if (success) {
95
111
  logger.debug({ title: "Performing success callback", type: "system", extra: values });
96
- onSuccessCallback.current?.(values as any);
112
+ if (opt?.invalidate) {
113
+ opt.invalidate.forEach((req) => cache.invalidate(req));
114
+ }
115
+ onSuccessCallback.current?.(paramsWithContext);
97
116
  } else {
98
117
  logger.debug({ title: "Performing error callback", type: "system", extra: values });
99
- onErrorCallback.current?.(values as any);
118
+ if (!willRetry) {
119
+ try {
120
+ opt?.rollback?.();
121
+ } catch {
122
+ // rollback threw — onError still fires
123
+ }
124
+ }
125
+ onErrorCallback.current?.(paramsWithContext);
126
+ }
127
+ onFinishedCallback.current?.(paramsWithContext);
128
+ if (!willRetry) {
129
+ optimisticResultsRef.current.delete(values.requestId);
100
130
  }
101
- onFinishedCallback.current?.(values);
102
131
  };
103
132
 
104
133
  // ******************
@@ -113,7 +142,7 @@ export const useRequestEvents = <R extends RequestInstance>({
113
142
  // This prevents the UI from flickering with { data: null, loading: false }
114
143
  if (isProcessing) return;
115
144
 
116
- const canDisableLoading = !loading && !dispatcher.hasRunningRequests(req.queryKey);
145
+ const canDisableLoading = !loading && !dispatcher.hasRunningRequests(scopeKey(req.queryKey, req.scope));
117
146
  if (loading || canDisableLoading) {
118
147
  actions.setLoading(loading);
119
148
  }
@@ -158,6 +187,15 @@ export const useRequestEvents = <R extends RequestInstance>({
158
187
  };
159
188
 
160
189
  const handleRemove = ({ requestId }: RequestEventType<R>) => {
190
+ const opt = optimisticResultsRef.current.get(requestId);
191
+ if (opt) {
192
+ try {
193
+ opt.rollback?.();
194
+ } catch {
195
+ // swallow — queue removal rollback failure
196
+ }
197
+ optimisticResultsRef.current.delete(requestId);
198
+ }
161
199
  removeLifecycleListener(requestId);
162
200
  };
163
201
 
@@ -172,7 +210,10 @@ export const useRequestEvents = <R extends RequestInstance>({
172
210
 
173
211
  const addCacheDataListener = (req: R) => {
174
212
  // Data handlers
175
- const loadingUnmount = requestManager.events.onLoadingByQueue(req.queryKey, handleGetLoadingEvent(req));
213
+ const loadingUnmount = requestManager.events.onLoadingByQueue(
214
+ scopeKey(req.queryKey, req.scope),
215
+ handleGetLoadingEvent(req),
216
+ );
176
217
  const getResponseUnmount = cache.events.onDataByKey<
177
218
  ExtractResponseType<R>,
178
219
  ExtractErrorType<R>,
@@ -194,7 +235,7 @@ export const useRequestEvents = <R extends RequestInstance>({
194
235
  // Lifecycle Listeners
195
236
  // ******************
196
237
 
197
- const addLifecycleListeners = (req: R, requestId?: string) => {
238
+ const addLifecycleListeners = (req: R, requestId?: string, optimisticResult?: OptimisticCallbackResult<any>) => {
198
239
  /**
199
240
  * useFetch handles requesting by general keys
200
241
  * This makes it possible to deduplicate requests from different places and share data
@@ -225,6 +266,9 @@ export const useRequestEvents = <R extends RequestInstance>({
225
266
  /**
226
267
  * useSubmit handles requesting by requestIds, this makes it possible to track single requests
227
268
  */
269
+ if (optimisticResult) {
270
+ optimisticResultsRef.current.set(requestId, optimisticResult);
271
+ }
228
272
  const requestRemove = requestManager.events.onRemoveById(requestId, handleRemove);
229
273
  const requestStartUnmount = requestManager.events.onRequestStartById(requestId, handleRequestStart());
230
274
  const responseStartUnmount = requestManager.events.onResponseStartById(requestId, handleResponseStart());
@@ -251,11 +295,13 @@ export const useRequestEvents = <R extends RequestInstance>({
251
295
  // ******************
252
296
 
253
297
  const abort = () => {
254
- const { abortKey } = request;
298
+ const ak = scopeKey(request.abortKey, request.scope);
255
299
  const requests = dispatcher.getAllRunningRequests();
256
300
  requests.forEach((requestData) => {
257
- if (requestData.request.abortKey === abortKey) {
258
- dispatcher.delete(requestData.request.queryKey, requestData.requestId, abortKey);
301
+ const reqAk = scopeKey(requestData.request.abortKey, requestData.request.scope);
302
+ if (reqAk === ak) {
303
+ const qk = scopeKey(requestData.request.queryKey, requestData.request.scope);
304
+ dispatcher.delete(qk, requestData.requestId, reqAk);
259
305
  }
260
306
  });
261
307
  };
@@ -1,9 +1,11 @@
1
- import {
1
+ import type {
2
2
  Dispatcher,
3
3
  ExtractErrorType,
4
4
  CacheValueType,
5
5
  ExtractResponseType,
6
+ ExtractMutationContextType,
6
7
  LoggerMethods,
8
+ OptimisticCallbackResult,
7
9
  RequestEventType,
8
10
  RequestInstance,
9
11
  RequestProgressEventType,
@@ -14,7 +16,7 @@ import {
14
16
  ResponseSuccessType,
15
17
  } from "@hyper-fetch/core";
16
18
 
17
- import { UseTrackedStateActions } from "helpers";
19
+ import type { UseTrackedStateActions } from "helpers";
18
20
 
19
21
  // Misc
20
22
  export type UseRequestEventsDataMap = { unmount: VoidFunction };
@@ -36,23 +38,23 @@ export type UseRequestEventsActionsType<T extends RequestInstance> = {
36
38
  */
37
39
  abort: () => void;
38
40
  /**
39
- * Helper hook listening on success response.
41
+ * Helper hook listening on success response. Includes `mutationContext` when `setOptimistic` is configured.
40
42
  */
41
43
  onSuccess: (callback: OnSuccessCallbackType<T>) => void;
42
44
  /**
43
- * Helper hook listening on error response.
45
+ * Helper hook listening on error response. Includes `mutationContext` when `setOptimistic` is configured.
44
46
  */
45
47
  onError: (callback: OnErrorCallbackType<T>) => void;
46
48
  /**
47
- * Helper hook listening on aborting of requests. Abort events are not triggering onError callbacks.
49
+ * Helper hook listening on aborting of requests. Includes `mutationContext` when `setOptimistic` is configured.
48
50
  */
49
51
  onAbort: (callback: OnErrorCallbackType<T>) => void;
50
52
  /**
51
- * Helper hook listening on request going into offline awaiting for network connection to be restored. It will not trigger onError when 'offline' mode is set on request.
53
+ * Helper hook listening on request going into offline awaiting for network connection to be restored.
52
54
  */
53
55
  onOfflineError: (callback: OnErrorCallbackType<T>) => void;
54
56
  /**
55
- * Helper hook listening on any response.
57
+ * Helper hook listening on any response. Includes `mutationContext` when `setOptimistic` is configured.
56
58
  */
57
59
  onFinished: (callback: OnFinishedCallbackType<T>) => void;
58
60
  /**
@@ -64,11 +66,11 @@ export type UseRequestEventsActionsType<T extends RequestInstance> = {
64
66
  */
65
67
  onResponseStart: (callback: OnStartCallbackType<T>) => void;
66
68
  /**
67
- * Helper hook listening on download progress ETA. We can later match given requests by their id's or request instance which holds all data which is being transferred.
69
+ * Helper hook listening on download progress ETA.
68
70
  */
69
71
  onDownloadProgress: (callback: OnProgressCallbackType) => void;
70
72
  /**
71
- * Helper hook listening on upload progress ETA. We can later match given requests by their id's or request instance which holds all data which is being transferred.
73
+ * Helper hook listening on upload progress ETA.
72
74
  */
73
75
  onUploadProgress: (callback: OnProgressCallbackType) => void;
74
76
  };
@@ -79,7 +81,11 @@ export type UseRequestEventsReturnType<T extends RequestInstance> = [
79
81
  {
80
82
  addCacheDataListener: (request: T) => VoidFunction;
81
83
  clearCacheDataListener: VoidFunction;
82
- addLifecycleListeners: (request: T, requestId?: string) => VoidFunction;
84
+ addLifecycleListeners: (
85
+ request: T,
86
+ requestId?: string,
87
+ optimisticResult?: OptimisticCallbackResult<any>,
88
+ ) => VoidFunction;
83
89
  removeLifecycleListener: (requestId: string) => void;
84
90
  clearLifecycleListeners: () => void;
85
91
  },
@@ -87,8 +93,9 @@ export type UseRequestEventsReturnType<T extends RequestInstance> = [
87
93
 
88
94
  // Lifecycle
89
95
 
90
- export type CallbackParameters<Request extends RequestInstance, ResponseType> = {
91
- response: ResponseType;
96
+ export type CallbackParameters<Request extends RequestInstance, Resp> = {
97
+ response: Resp;
98
+ mutationContext: ExtractMutationContextType<Request> | undefined;
92
99
  } & Omit<RequestResponseEventType<Request>, "response">;
93
100
 
94
101
  export type OnSuccessCallbackType<Request extends RequestInstance> = (
@@ -1,6 +1,6 @@
1
- import { SocketInstance } from "@hyper-fetch/sockets";
1
+ import type { SocketInstance } from "@hyper-fetch/sockets";
2
2
 
3
- import { UseSocketStateType } from "./use-socket-state.types";
3
+ import type { UseSocketStateType } from "./use-socket-state.types";
4
4
 
5
5
  export const initialSocketState: UseSocketStateType<SocketInstance> = {
6
6
  data: null,
@@ -1,15 +1,13 @@
1
- import { SocketInstance, ExtractSocketExtraType } from "@hyper-fetch/sockets";
2
- import { useDidMount, useDidUpdate, useForceUpdate } from "@better-hooks/lifecycle";
3
- import { useRef } from "react";
1
+ import type { SocketInstance, ExtractSocketExtraType } from "@hyper-fetch/sockets";
2
+ import { useDidMount, useDidUpdate } from "@better-hooks/lifecycle";
3
+ import { useCallback, useRef, useSyncExternalStore } from "react";
4
4
 
5
- import { UseSocketStateType, initialSocketState, UseSocketStateProps } from "helpers";
5
+ import type { UseSocketStateType, UseSocketStateProps } from "helpers";
6
6
 
7
7
  export const useSocketState = <DataType, Socket extends SocketInstance>(
8
8
  socket: Socket,
9
9
  { dependencyTracking }: UseSocketStateProps,
10
10
  ) => {
11
- const forceUpdate = useForceUpdate();
12
-
13
11
  const onDisconnectCallback = useRef<null | VoidFunction>(null);
14
12
  const onErrorCallback = useRef<null | ((event: any) => void)>(null);
15
13
  const onConnectedCallback = useRef<null | VoidFunction>(null);
@@ -17,16 +15,45 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
17
15
  const onReconnectingCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
18
16
  const onReconnectingFailedCallback = useRef<null | ((data: { attempts: number }) => void)>(null);
19
17
 
20
- const state = useRef<UseSocketStateType<Socket, DataType>>(initialSocketState);
18
+ const state = useRef<UseSocketStateType<Socket, DataType>>({
19
+ data: null,
20
+ extra: null,
21
+ connected: socket.adapter.connected,
22
+ connecting: socket.adapter.connecting,
23
+ timestamp: null,
24
+ });
21
25
  const renderKeys = useRef<Array<keyof UseSocketStateType<Socket, DataType>>>([]);
22
26
 
27
+ // ******************
28
+ // useSyncExternalStore
29
+ // ******************
30
+
31
+ const versionRef = useRef(0);
32
+ const listenerRef = useRef<(() => void) | null>(null);
33
+
34
+ const subscribe = useCallback((listener: () => void) => {
35
+ listenerRef.current = listener;
36
+ return () => {
37
+ listenerRef.current = null;
38
+ };
39
+ }, []);
40
+
41
+ const getSnapshot = useCallback(() => versionRef.current, []);
42
+
43
+ useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
44
+
45
+ const emitChange = () => {
46
+ versionRef.current += 1;
47
+ listenerRef.current?.();
48
+ };
49
+
23
50
  // ******************
24
51
  // Dependency Tracking
25
52
  // ******************
26
53
 
27
54
  const renderKeyTrigger = (keys: Array<keyof UseSocketStateType<Socket, DataType>>) => {
28
55
  const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
29
- if (shouldRerender) forceUpdate();
56
+ if (shouldRerender) emitChange();
30
57
  };
31
58
 
32
59
  const setRenderKey = (renderKey: keyof UseSocketStateType<Socket, DataType>) => {
@@ -41,9 +68,6 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
41
68
 
42
69
  useDidUpdate(
43
70
  () => {
44
- state.current.connected = socket.adapter.connected;
45
- state.current.connecting = socket.adapter.connecting;
46
-
47
71
  const handleDependencyTracking = () => {
48
72
  if (!dependencyTracking) {
49
73
  Object.keys(state.current).forEach((key) => setRenderKey(key as Parameters<typeof setRenderKey>[0]));
@@ -71,16 +95,26 @@ export const useSocketState = <DataType, Socket extends SocketInstance>(
71
95
  },
72
96
  setConnected: (connected: boolean) => {
73
97
  state.current.connected = connected;
74
- renderKeyTrigger(["data"]);
98
+ renderKeyTrigger(["connected"]);
75
99
  },
76
100
  setConnecting: (connecting: boolean) => {
77
101
  state.current.connecting = connecting;
78
- renderKeyTrigger(["data"]);
102
+ renderKeyTrigger(["connecting"]);
79
103
  },
80
104
  setTimestamp: (timestamp: number | null) => {
81
105
  state.current.timestamp = timestamp;
82
106
  renderKeyTrigger(["timestamp"]);
83
107
  },
108
+ clearState: () => {
109
+ state.current = {
110
+ data: null,
111
+ extra: null,
112
+ connected: false,
113
+ connecting: false,
114
+ timestamp: null,
115
+ };
116
+ renderKeyTrigger(Object.keys(state.current) as (keyof UseSocketStateType<Socket, DataType>)[]);
117
+ },
84
118
  };
85
119
 
86
120
  const callbacks = {
@@ -1,4 +1,4 @@
1
- import { ExtractSocketExtraType, SocketInstance } from "@hyper-fetch/sockets";
1
+ import type { ExtractSocketExtraType, SocketInstance } from "@hyper-fetch/sockets";
2
2
 
3
3
  export type UseSocketStateType<Socket extends SocketInstance, DataType = any> = {
4
4
  data: DataType | null;
@@ -1,4 +1,4 @@
1
- import { UseTrackedStateType } from "./use-tracked-state.types";
1
+ import type { UseTrackedStateType } from "./use-tracked-state.types";
2
2
 
3
3
  export const initialState: UseTrackedStateType = {
4
4
  data: null,
@@ -1,6 +1,6 @@
1
1
  /* eslint-disable @typescript-eslint/naming-convention */
2
- import { useDidUpdate, useForceUpdate } from "@better-hooks/lifecycle";
3
- import {
2
+ import { useDidUpdate } from "@better-hooks/lifecycle";
3
+ import type {
4
4
  ExtractErrorType,
5
5
  CacheValueType,
6
6
  ExtractResponseType,
@@ -9,16 +9,23 @@ import {
9
9
  ExtractAdapterExtraType,
10
10
  ResponseType,
11
11
  } from "@hyper-fetch/core";
12
- import { useRef } from "react";
12
+ import { scopeKey } from "@hyper-fetch/core";
13
+ import { useCallback, useRef, useSyncExternalStore } from "react";
13
14
 
14
15
  import { isEqual } from "utils";
15
- import {
16
+ import type {
16
17
  UseTrackedStateActions,
17
18
  UseTrackedStateType,
18
19
  UseTrackedStateProps,
19
20
  UseTrackedStateReturn,
20
21
  } from "./use-tracked-state.types";
21
- import { getInitialState, getIsInitiallyLoading, getValidCacheData, isStaleCacheData } from "./use-tracked-state.utils";
22
+ import {
23
+ getInitialState,
24
+ getIsInitiallyLoading,
25
+ getShouldClearState,
26
+ getValidCacheData,
27
+ isStaleCacheData,
28
+ } from "./use-tracked-state.utils";
22
29
 
23
30
  /**
24
31
  *
@@ -34,24 +41,47 @@ export const useTrackedState = <T extends RequestInstance>({
34
41
  initialResponse,
35
42
  deepCompare,
36
43
  dependencyTracking,
44
+ keepPreviousData = "auto",
37
45
  disabled,
38
46
  revalidate,
39
47
  }: UseTrackedStateProps<T>): UseTrackedStateReturn<T> => {
40
48
  const { client, cacheKey, queryKey, staleTime, unstable_responseMapper } = request;
41
49
  const { cache } = client;
42
50
 
43
- const forceUpdate = useForceUpdate();
44
-
45
51
  const state = useRef<UseTrackedStateType<T>>(getInitialState({ initialResponse, dispatcher, request, disabled }));
46
52
  const renderKeys = useRef<Array<keyof UseTrackedStateType<T>>>([]);
47
53
  const isProcessingData = useRef("");
54
+ const previousCacheKey = useRef(cacheKey);
55
+
56
+ // ******************
57
+ // useSyncExternalStore
58
+ // ******************
59
+
60
+ const versionRef = useRef(0);
61
+ const listenerRef = useRef<(() => void) | null>(null);
62
+
63
+ const subscribe = useCallback((listener: () => void) => {
64
+ listenerRef.current = listener;
65
+ return () => {
66
+ listenerRef.current = null;
67
+ };
68
+ }, []);
69
+
70
+ const getSnapshot = useCallback(() => versionRef.current, []);
71
+
72
+ useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
73
+
74
+ const emitChange = () => {
75
+ versionRef.current += 1;
76
+ listenerRef.current?.();
77
+ };
48
78
 
49
79
  // ******************
50
80
  // Utils
51
81
  // ******************
52
82
 
53
83
  const getStaleStatus = (): boolean => {
54
- const cacheData = cache.get(cacheKey);
84
+ const cacheData = cache.get(scopeKey(cacheKey, request.scope));
55
85
  return !cacheData || isStaleCacheData(staleTime, cacheData?.responseTimestamp);
56
86
  };
57
87
 
@@ -61,7 +91,7 @@ export const useTrackedState = <T extends RequestInstance>({
61
91
 
62
92
  const renderKeyTrigger = (keys: Array<keyof UseTrackedStateType>) => {
63
93
  const shouldRerender = renderKeys.current.some((renderKey) => keys.includes(renderKey));
64
- if (shouldRerender) forceUpdate();
94
+ if (shouldRerender) emitChange();
65
95
  };
66
96
 
67
97
  const setRenderKey = (renderKey: keyof UseTrackedStateType) => {
@@ -76,26 +106,34 @@ export const useTrackedState = <T extends RequestInstance>({
76
106
 
77
107
  useDidUpdate(
78
108
  () => {
109
+ const oldKey = previousCacheKey.current;
110
+ previousCacheKey.current = cacheKey;
111
+
79
112
  // Get cache state
80
113
  const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(cacheKey);
81
114
  const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
82
115
 
83
- // Handle initial loading state
84
- state.current.loading = getIsInitiallyLoading({
85
- queryKey: request.queryKey,
86
- dispatcher,
87
- disabled,
88
- revalidate,
89
- hasState: !!cacheState,
90
- });
91
-
92
- if (cacheState) {
93
- // Don't update the state when we are fetching data for new cacheKey
94
- // So on paginated page we will have previous page access until the new one will be fetched
95
- // However: When we have some cached data, we can use it right away
116
+ // Determine whether to clear state based on keepPreviousData mode
117
+ const shouldClear = getShouldClearState(keepPreviousData, oldKey, cacheKey);
118
+
119
+ if (shouldClear && !cacheState) {
120
+ // Reset state to initial values when no cached data exists for the new key
121
+ const resetState = getInitialState({ initialResponse, dispatcher, request, disabled, revalidate });
122
+ state.current = resetState;
123
+ renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T>)[]);
124
+ } else if (cacheState) {
125
+ state.current.loading = getIsInitiallyLoading({
126
+ queryKey: scopeKey(request.queryKey, request.scope),
127
+ dispatcher,
128
+ disabled,
129
+ revalidate,
130
+ hasState: true,
131
+ });
96
132
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
97
133
  setCacheData(cacheState);
98
134
  }
135
+ // When state is preserved and no cache exists (e.g. query param change in "auto" mode),
136
+ // don't update loading on the ref — let the dispatcher's loading event handle it (#126)
99
137
  },
100
138
  [cacheKey, queryKey],
101
139
  true,
@@ -274,6 +312,20 @@ export const useTrackedState = <T extends RequestInstance>({
274
312
  state.current.requestTimestamp = getTimestamp(state.current.requestTimestamp);
275
313
  renderKeyTrigger(["requestTimestamp"]);
276
314
  },
315
+ clearState: () => {
316
+ state.current = {
317
+ data: null,
318
+ error: null,
319
+ loading: false,
320
+ status: null,
321
+ success: false,
322
+ extra: null,
323
+ retries: 0,
324
+ responseTimestamp: null,
325
+ requestTimestamp: null,
326
+ } as UseTrackedStateType<T>;
327
+ renderKeyTrigger(Object.keys(state.current) as (keyof UseTrackedStateType<T>)[]);
328
+ },
277
329
  };
278
330
 
279
331
  return [state.current, actions, { setRenderKey, setCacheData, getStaleStatus, getIsDataProcessing }];
@@ -1,4 +1,4 @@
1
- import {
1
+ import type {
2
2
  Dispatcher,
3
3
  ExtractErrorType,
4
4
  CacheValueType,
@@ -13,7 +13,7 @@ import {
13
13
  LoggerMethods,
14
14
  } from "@hyper-fetch/core";
15
15
 
16
- import { isEqual } from "utils";
16
+ import type { isEqual } from "utils";
17
17
 
18
18
  export type UseTrackedStateProps<T extends RequestInstance> = {
19
19
  request: T;
@@ -22,6 +22,7 @@ export type UseTrackedStateProps<T extends RequestInstance> = {
22
22
  dispatcher: Dispatcher<ExtractAdapterType<T>>;
23
23
  dependencyTracking: boolean;
24
24
  deepCompare: boolean | typeof isEqual;
25
+ keepPreviousData?: "auto" | "preserve" | "clean";
25
26
  disabled?: boolean;
26
27
  revalidate?: boolean;
27
28
  };
@@ -122,4 +123,8 @@ export type UseTrackedStateActions<T extends RequestInstance> = {
122
123
  * If you need to update cache data use client.cache.update() method.
123
124
  */
124
125
  setRequestTimestamp: (timestamp: CacheSetState<Date>) => void;
126
+ /**
127
+ * Reset all state fields to their initial values (data, error, status, extra → null, loading → false, etc.).
128
+ */
129
+ clearState: () => void;
125
130
  };
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/naming-convention */
2
- import {
2
+ import type {
3
3
  CacheValueType,
4
4
  NullableType,
5
5
  RequestInstance,
@@ -13,8 +13,41 @@ import {
13
13
  ExtractAdapterStatusType,
14
14
  ResponseType,
15
15
  } from "@hyper-fetch/core";
16
+ import { scopeKey } from "@hyper-fetch/core";
17
+
18
+ import type { UseTrackedStateType } from "helpers";
19
+ import { initialState } from "helpers";
20
+
21
+ /**
22
+ * Extracts the "identity" portion of a cache key (method + endpoint with resolved params),
23
+ * stripping the query params part. Cache keys follow the format: `method_endpoint_queryParams`.
24
+ */
25
+ const getCacheKeyIdentity = (cacheKey: string): string => {
26
+ const lastUnderscoreIndex = cacheKey.lastIndexOf("_");
27
+ if (lastUnderscoreIndex === -1) return cacheKey;
28
+ return cacheKey.substring(0, lastUnderscoreIndex);
29
+ };
16
30
 
17
- import { initialState, UseTrackedStateType } from "helpers";
31
+ /**
32
+ * Determines whether state should be cleared when the cache key changes.
33
+ *
34
+ * - `"clean"` — always clear
35
+ * - `"preserve"` — never clear
36
+ * - `"auto"` — clear when the resource identity changed (URL params), preserve when only query params changed
37
+ */
38
+ export const getShouldClearState = (
39
+ mode: "auto" | "preserve" | "clean",
40
+ oldCacheKey: string,
41
+ newCacheKey: string,
42
+ ): boolean => {
43
+ if (oldCacheKey === newCacheKey) return false;
44
+
45
+ if (mode === "clean") return true;
46
+ if (mode === "preserve") return false;
47
+
48
+ // "auto" — compare the identity part (method + endpoint with params)
49
+ return getCacheKeyIdentity(oldCacheKey) !== getCacheKeyIdentity(newCacheKey);
50
+ };
18
51
 
19
52
  export const getDetailsState = (
20
53
  state?: UseTrackedStateType<RequestInstance>,
@@ -24,6 +57,7 @@ export const getDetailsState = (
24
57
  retries: state?.retries || 0,
25
58
  isCanceled: false,
26
59
  isOffline: false,
60
+ willRetry: false,
27
61
  addedTimestamp: +new Date(),
28
62
  triggerTimestamp: +new Date(),
29
63
  requestTimestamp: +new Date(),
@@ -61,6 +95,7 @@ export const getValidCacheData = <T extends RequestInstance>(
61
95
  staleTime: 1000,
62
96
  version: request.client.cache.version,
63
97
  cacheKey: request.cacheKey,
98
+ scope: request.scope,
64
99
  cacheTime: request.cacheTime,
65
100
  requestTimestamp: initialResponse?.requestTimestamp ?? +new Date(),
66
101
  responseTimestamp: initialResponse?.responseTimestamp ?? +new Date(),
@@ -113,11 +148,11 @@ export const getInitialState = <T extends RequestInstance>({
113
148
  const { client, cacheKey, unstable_responseMapper } = request;
114
149
  const { cache } = client;
115
150
 
116
- const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(cacheKey);
151
+ const cacheData = cache.get<ExtractResponseType<T>, ExtractErrorType<T>>(scopeKey(cacheKey, request.scope));
117
152
  const cacheState = getValidCacheData<T>(request, initialResponse, cacheData);
118
153
 
119
154
  const initialLoading = getIsInitiallyLoading({
120
- queryKey: request.queryKey,
155
+ queryKey: scopeKey(request.queryKey, request.scope),
121
156
  dispatcher,
122
157
  disabled,
123
158
  revalidate,
@@ -1,8 +1,8 @@
1
1
  import { useDidMount } from "@better-hooks/lifecycle";
2
- import { ClientInstance } from "@hyper-fetch/core";
2
+ import type { ClientInstance } from "@hyper-fetch/core";
3
3
  import { useState } from "react";
4
4
 
5
- import { UseAppManagerReturnType } from "hooks/use-app-manager";
5
+ import type { UseAppManagerReturnType } from "hooks/use-app-manager";
6
6
 
7
7
  export const useAppManager = <Client extends ClientInstance>(client: Client): UseAppManagerReturnType => {
8
8
  const [online, setIsOnline] = useState(client.appManager.isOnline);