@hyper-fetch/react 9.6.1 → 9.7.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 (98) 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-helpers.spec.tsx +455 -0
  47. package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +6 -0
  48. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  49. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  50. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  51. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  52. package/__tests__/utils/gate.utils.ts +103 -0
  53. package/__tests__/utils/gated-client.utils.ts +158 -0
  54. package/__tests__/utils/helpers.utils.ts +19 -0
  55. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  56. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  57. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  58. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  59. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  60. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  61. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  62. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  63. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  64. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  65. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  66. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  67. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  68. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  69. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  70. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  71. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  72. package/dist/hooks/use-submit/use-submit.constants.d.ts +1 -1
  73. package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -1
  74. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  75. package/dist/hooks/use-submit/use-submit.types.d.ts +6 -1
  76. package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -1
  77. package/dist/index.mjs +633 -346
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/provider/provider.d.ts.map +1 -1
  80. package/package.json +1 -1
  81. package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
  82. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  83. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  84. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  85. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  86. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  87. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  88. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  89. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  90. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  91. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  92. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  93. package/src/hooks/use-submit/use-submit.constants.ts +3 -1
  94. package/src/hooks/use-submit/use-submit.hooks.ts +167 -53
  95. package/src/hooks/use-submit/use-submit.types.ts +6 -0
  96. package/src/provider/provider.tsx +9 -1
  97. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  98. package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
@@ -1,3 +1,4 @@
1
+ import { useForceUpdate } from "@better-hooks/lifecycle";
1
2
  import { useDebounce, useThrottle } from "@better-hooks/performance";
2
3
  import type {
3
4
  ExtractAdapterResolvedType,
@@ -9,13 +10,13 @@ import type {
9
10
  RequestSendType,
10
11
  ExtractAdapterType,
11
12
  } from "@hyper-fetch/core";
12
- import { sendRequest } from "@hyper-fetch/core";
13
+ import { runUserCode, sendRequest } from "@hyper-fetch/core";
13
14
  import type { UseTrackedStateType } from "helpers";
14
15
  import { useTrackedState, useRequestEvents } from "helpers";
15
16
  import type { UseSubmitOptionsType, UseSubmitReturnType } from "hooks/use-submit";
16
17
  import { useSubmitDefaultOptions } from "hooks/use-submit";
17
18
  import { useProvider } from "provider";
18
- import { useEffect, useMemo, useRef } from "react";
19
+ import { useCallback, useEffect, useMemo, useRef } from "react";
19
20
  import { createTrackedProxy, getBounceData } from "utils";
20
21
 
21
22
  /**
@@ -64,36 +65,40 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
64
65
  interval: bounceTime,
65
66
  timeout: "bounceTimeout" in mergedOptions ? mergedOptions.bounceTimeout : bounceTime,
66
67
  });
68
+ const forceUpdate = useForceUpdate();
69
+ // Resolvers of the submit calls waiting for the bounced request
67
70
  const bounceResolver = useRef<
68
- (
69
- value: ResponseType<
70
- ExtractResponseType<RequestType>,
71
- ExtractErrorType<RequestType>,
72
- ExtractAdapterType<RequestType>
73
- >,
74
- ) => void
75
- >(() => null);
71
+ | null
72
+ | ((
73
+ value: ResponseType<
74
+ ExtractResponseType<RequestType>,
75
+ ExtractErrorType<RequestType>,
76
+ ExtractAdapterType<RequestType>
77
+ >,
78
+ ) => void)
79
+ >(null);
76
80
 
77
81
  const bounceData = bounceType === "throttle" ? requestThrottle : requestDebounce;
82
+ // Bounce state shown by this render
83
+ const isBounceActive = bounceData.active;
78
84
  const bounceFunction = bounceType === "throttle" ? requestThrottle.throttle : requestDebounce.debounce;
79
85
 
80
86
  /**
81
87
  * State handler with optimization for rerendering, that hooks into the cache state and dispatchers queues
82
88
  */
83
- const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<
84
- RequestType,
85
- TSelected
86
- >({
87
- logger,
88
- request,
89
- dispatcher,
90
- initialResponse,
91
- deepCompare: deepCompare as boolean,
92
- dependencyTracking: dependencyTracking as boolean,
93
- // Read directly from options - functions are not part of the memoized options key
94
- select: options?.select,
95
- structuralSharing,
96
- });
89
+ const [state, actions, { setRenderKey, setCacheData, getIsDataProcessing }] = useTrackedState<RequestType, TSelected>(
90
+ {
91
+ logger,
92
+ request,
93
+ dispatcher,
94
+ initialResponse,
95
+ deepCompare: deepCompare as boolean,
96
+ dependencyTracking: dependencyTracking as boolean,
97
+ // Read directly from options - functions are not part of the memoized options key
98
+ select: options?.select,
99
+ structuralSharing,
100
+ },
101
+ );
97
102
 
98
103
  /**
99
104
  * Handles the data exchange with the core logic - responses, loading, downloading etc
@@ -107,37 +112,71 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
107
112
  getIsDataProcessing,
108
113
  });
109
114
 
110
- const { addCacheDataListener, addLifecycleListeners } = listeners;
115
+ const { addCacheDataListener, addLifecycleListeners, removeLifecycleListener } = listeners;
111
116
 
112
117
  // ******************
113
118
  // Submitting
114
119
  // ******************
115
120
 
116
- const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {
117
- const requestClone = request.clone(submitOptions as any) as unknown as RequestType;
121
+ /**
122
+ * Response for the submit calls which did not send any request. The submit promise never rejects,
123
+ * so the reason is returned as an error response.
124
+ */
125
+ const getNotSentResponse = (message: string) => {
126
+ const timestamp = Date.now();
127
+ return {
128
+ data: null,
129
+ error: new Error(message),
130
+ status: null,
131
+ success: false,
132
+ extra: request.client.adapter.defaultExtra,
133
+ requestTimestamp: timestamp,
134
+ responseTimestamp: timestamp,
135
+ } as ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>;
136
+ };
137
+
138
+ /**
139
+ * Bounced submit calls wait for the request to be triggered. When it will not happen anymore (bounce got reset,
140
+ * call got dropped or the hook unmounted) we have to resolve them - the submit promise can never stay pending.
141
+ */
142
+ const resolveBouncedCalls = (message: string) => {
143
+ const resolvePending = bounceResolver.current;
144
+ bounceResolver.current = null;
145
+ resolvePending?.(getNotSentResponse(message));
146
+ };
118
147
 
148
+ const handleSubmit: RequestSendType<RequestType> = (submitOptions?: RequestSendOptionsType<RequestType>) => {
119
149
  if (disabled) {
120
150
  logger.warning({ title: `Cannot submit request`, type: "system", extra: { disabled, submitOptions } });
121
- return Promise.resolve({
122
- data: null,
123
- error: new Error("Cannot submit request. Option 'disabled' is enabled"),
124
- status: null,
125
- extra: request.client.adapter.defaultExtra,
126
- }) as Promise<
127
- ResponseType<ExtractResponseType<RequestType>, ExtractErrorType<RequestType>, ExtractAdapterType<RequestType>>
128
- >;
151
+ return Promise.resolve(getNotSentResponse("Cannot submit request. Option 'disabled' is enabled"));
129
152
  }
130
153
 
154
+ const { optimistic: submitOptimistic, ...cloneOptions } = submitOptions || {};
155
+ const requestClone = request.clone(cloneOptions as any) as unknown as RequestType;
156
+ // Read directly from options - functions are not part of the memoized options key
157
+ const optimistic = submitOptimistic ?? options?.optimistic;
158
+
131
159
  const triggerRequest = () => {
132
160
  addCacheDataListener(requestClone);
133
161
 
134
162
  const configuration: RequestSendOptionsType<RequestType> = {
135
163
  dispatcherType: "submit",
136
164
  ...(submitOptions as RequestSendOptionsType<RequestType>),
165
+ optimistic,
137
166
  onBeforeSent: (data) => {
167
+ // Deduplicated submit joins the request which is already in flight and shares its id.
168
+ // We keep a single set of listeners for it, so the callbacks fire once per response.
169
+ removeLifecycleListener(data.requestId);
138
170
  addLifecycleListeners(requestClone, data.requestId, data.mutationContext);
139
171
  submitOptions?.onBeforeSent?.(data);
140
172
  },
173
+ onResponse: (data) => {
174
+ // This is the final response (retries and waiting for the network are over) and our listeners already
175
+ // handled it. Dispatcher does not announce the removal of every request (e.g. the canceled ones),
176
+ // so we release the listeners here to not leak them.
177
+ removeLifecycleListener(data.requestId);
178
+ submitOptions?.onResponse?.(data);
179
+ },
141
180
  };
142
181
 
143
182
  return sendRequest(requestClone, configuration);
@@ -159,20 +198,33 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
159
198
  >,
160
199
  ) => {
161
200
  // Trigger previous awaiting calls to resolve together in bounced batches
162
- bouncedResolve(value);
201
+ bouncedResolve?.(value);
163
202
  resolve(value);
164
203
  };
165
204
 
205
+ let isTriggered = false;
206
+
166
207
  // Start bounce
167
208
  bounceFunction(async () => {
209
+ isTriggered = true;
168
210
  // We will always resolve previous calls as we stack the callbacks together until bounce function trigger
169
211
  const callback = bounceResolver.current;
170
212
  // Clean bounce resolvers to start the new stack
171
- bounceResolver.current = () => null;
213
+ bounceResolver.current = null;
172
214
 
173
215
  const value = await triggerRequest();
174
- callback(value);
216
+ callback?.(value);
175
217
  });
218
+
219
+ // Throttle without the trailing timeout drops the calls made during the interval - nothing will trigger them
220
+ if (!isTriggered && !bounceData.active) {
221
+ resolveBouncedCalls("Request was not sent. Submit call got dropped by the throttle");
222
+ }
223
+
224
+ // Throttle does not notify about the call it holds, so the returned bounce state would stay outdated
225
+ if (bounceData.active !== isBounceActive) {
226
+ forceUpdate();
227
+ }
176
228
  } else {
177
229
  const value = await triggerRequest();
178
230
  resolve(value);
@@ -187,35 +239,97 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
187
239
  // Invalidation
188
240
  // ******************
189
241
 
190
- const refetch = () => {
242
+ const handleRefetch = () => {
191
243
  cache.invalidate(request);
192
244
  };
193
245
 
194
246
  // ******************
195
- // Misc
247
+ // Stable methods
248
+ // ******************
249
+
250
+ // The returned methods keep their identity between renders (safe to use in the dependency arrays)
251
+ // and always work with the request and options from the latest render
252
+ const latest = useRef({ handleSubmit, handleRefetch, resolveBouncedCalls });
253
+ latest.current = { handleSubmit, handleRefetch, resolveBouncedCalls };
254
+
255
+ const submit = useCallback(
256
+ ((submitOptions?: RequestSendOptionsType<RequestType>) =>
257
+ (latest.current.handleSubmit as (options?: RequestSendOptionsType<RequestType>) => unknown)(
258
+ submitOptions,
259
+ )) as unknown as RequestSendType<RequestType>,
260
+ [],
261
+ );
262
+
263
+ const refetch = useCallback(() => latest.current.handleRefetch(), []);
264
+
265
+ // ******************
266
+ // Bounce
196
267
  // ******************
197
268
 
198
- const handlers = {
199
- onSubmitSuccess: callbacks.onSuccess,
200
- onSubmitError: callbacks.onError,
201
- onSubmitFinished: callbacks.onFinished,
202
- onSubmitRequestStart: callbacks.onRequestStart,
203
- onSubmitResponseStart: callbacks.onResponseStart,
204
- onSubmitDownloadProgress: callbacks.onDownloadProgress,
205
- onSubmitUploadProgress: callbacks.onUploadProgress,
206
- onSubmitOfflineError: callbacks.onOfflineError,
207
- onSubmitAbort: callbacks.onAbort,
269
+ const resetBounce = () => {
270
+ const wasActive = bounceData.active;
271
+ bounceData.reset();
272
+ resolveBouncedCalls("Request was not sent. Bounce got reset before triggering the request");
273
+ // Reset does not notify about the change on its own
274
+ if (wasActive) {
275
+ forceUpdate();
276
+ }
208
277
  };
209
278
 
279
+ // ******************
280
+ // Misc
281
+ // ******************
282
+
283
+ const handlers = useMemo(() => {
284
+ /**
285
+ * Callbacks run inside of the request lifecycle. Error thrown by one of them would break it - the request
286
+ * would never finish and it would block the queue. Such error is thrown outside of the lifecycle instead,
287
+ * the same way as the errors of every other callback, listener and plugin.
288
+ */
289
+ const protect = <Args extends unknown[]>(callback: (...args: Args) => void | Promise<void>) => {
290
+ return (...args: Args): void => {
291
+ runUserCode(() => {
292
+ callback(...args);
293
+ });
294
+ };
295
+ };
296
+
297
+ return {
298
+ onSubmitSuccess: (callback: Parameters<typeof callbacks.onSuccess>[0]) => callbacks.onSuccess(protect(callback)),
299
+ onSubmitError: (callback: Parameters<typeof callbacks.onError>[0]) => callbacks.onError(protect(callback)),
300
+ onSubmitFinished: (callback: Parameters<typeof callbacks.onFinished>[0]) =>
301
+ callbacks.onFinished(protect(callback)),
302
+ onSubmitRequestStart: (callback: Parameters<typeof callbacks.onRequestStart>[0]) =>
303
+ callbacks.onRequestStart(protect(callback)),
304
+ onSubmitResponseStart: (callback: Parameters<typeof callbacks.onResponseStart>[0]) =>
305
+ callbacks.onResponseStart(protect(callback)),
306
+ onSubmitDownloadProgress: (callback: Parameters<typeof callbacks.onDownloadProgress>[0]) =>
307
+ callbacks.onDownloadProgress(protect(callback) as typeof callback),
308
+ onSubmitUploadProgress: (callback: Parameters<typeof callbacks.onUploadProgress>[0]) =>
309
+ callbacks.onUploadProgress(protect(callback) as typeof callback),
310
+ onSubmitOfflineError: (callback: Parameters<typeof callbacks.onOfflineError>[0]) =>
311
+ callbacks.onOfflineError(protect(callback)),
312
+ onSubmitAbort: (callback: Parameters<typeof callbacks.onAbort>[0]) => callbacks.onAbort(protect(callback)),
313
+ };
314
+ }, [callbacks]);
315
+
210
316
  // ******************
211
317
  // Lifecycle
212
318
  // ******************
213
319
 
214
320
  // Plain effect on purpose - StrictMode runs mount, cleanup and mount again,
215
- // so a mount-once guard would leave the hook without the cache subscription
321
+ // so a mount-once guard would leave the hook without the cache subscription.
322
+ // When the request changes, we follow the data of the new one.
216
323
  useEffect(() => {
217
324
  addCacheDataListener(request);
218
325
  // eslint-disable-next-line react-hooks/exhaustive-deps
326
+ }, [request.cacheKey, request.queryKey, request.scope]);
327
+
328
+ // Bounce timers get cleared on unmount, so the waiting submit calls would never get resolved
329
+ useEffect(() => {
330
+ return () => {
331
+ latest.current.resolveBouncedCalls("Request was not sent. Hook got unmounted before triggering the request");
332
+ };
219
333
  }, []);
220
334
 
221
335
  const setSubmitRenderKey = (key: string) => {
@@ -236,7 +350,7 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
236
350
 
237
351
  return createTrackedProxy(
238
352
  {
239
- submit: handleSubmit,
353
+ submit,
240
354
  data: state.data,
241
355
  error: state.error,
242
356
  submitting: state.loading,
@@ -249,7 +363,7 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
249
363
  abort: callbacks.abort,
250
364
  ...actions,
251
365
  ...handlers,
252
- bounce: getBounceData(bounceData),
366
+ bounce: { ...getBounceData(bounceData), reset: resetBounce },
253
367
  refetch,
254
368
  },
255
369
  trackedKeys,
@@ -2,6 +2,7 @@ import type {
2
2
  ExtractAdapterResolvedType,
3
3
  ExtractResponseType,
4
4
  NullableType,
5
+ OptimisticSendOptionType,
5
6
  RequestInstance,
6
7
  RequestSendType,
7
8
  } from "@hyper-fetch/core";
@@ -47,6 +48,11 @@ export type UseSubmitOptionsType<T extends RequestInstance, TSelected = ExtractR
47
48
  * Keep references of the unchanged parts of the selected data between updates (default true).
48
49
  */
49
50
  structuralSharing?: boolean;
51
+ /**
52
+ * Optimistic update of every submit from this hook - `optimistic()` operations or a callback like the one of
53
+ * `setOptimistic`. Replaces the request's own optimistic callback; `submit({ optimistic })` replaces this one.
54
+ */
55
+ optimistic?: OptimisticSendOptionType<T>;
50
56
  } & (
51
57
  | {
52
58
  /**
@@ -1,4 +1,5 @@
1
- import React, { useContext, useMemo, useState } from "react";
1
+ import React, { useContext, useMemo, useRef, useState } from "react";
2
+ import { isEqual } from "utils";
2
3
 
3
4
  import type { ProviderProps, ProviderValueType } from "./provider.types";
4
5
 
@@ -15,6 +16,13 @@ const ConfigContext = React.createContext<ProviderValueType>({
15
16
  export const Provider = ({ children, config }: ProviderProps) => {
16
17
  const [currentConfig, setConfig] = useState(config || {});
17
18
 
19
+ // Follow the changes of the config prop - inline objects with the same values do not cause updates
20
+ const previousConfig = useRef(config);
21
+ if (!isEqual(previousConfig.current, config)) {
22
+ previousConfig.current = config;
23
+ setConfig(config || {});
24
+ }
25
+
18
26
  const value = useMemo(() => {
19
27
  const contextValue: ProviderValueType = { config: currentConfig, setConfig };
20
28
  return contextValue;
@@ -1,36 +0,0 @@
1
- import { createHttpMockingServer } from "@hyper-fetch/testing";
2
-
3
- import { client } from "../../utils";
4
-
5
- const { resetMocks, startServer, stopServer } = createHttpMockingServer();
6
-
7
- describe("useFetch [ Pagination ]", () => {
8
- beforeAll(() => {
9
- startServer();
10
- });
11
-
12
- afterEach(() => {
13
- resetMocks();
14
- });
15
-
16
- afterAll(() => {
17
- stopServer();
18
- });
19
-
20
- beforeEach(() => {
21
- vi.resetModules();
22
- client.clear();
23
- });
24
-
25
- describe("when request query params are changed", () => {
26
- it("should allow to see previous results until new page is loaded", async () => {
27
- // TODO
28
- });
29
- it("should not override previous results by initialData", async () => {
30
- // TODO
31
- });
32
- it("should cache pages on change", async () => {
33
- // TODO
34
- });
35
- });
36
- });
@@ -1,38 +0,0 @@
1
- import { createHttpMockingServer } from "@hyper-fetch/testing";
2
-
3
- const { resetMocks, startServer, stopServer } = createHttpMockingServer();
4
-
5
- describe("useFetch [ Retry ]", () => {
6
- beforeAll(() => {
7
- startServer();
8
- });
9
-
10
- afterEach(() => {
11
- resetMocks();
12
- });
13
-
14
- afterAll(() => {
15
- stopServer();
16
- });
17
-
18
- beforeEach(() => {
19
- vi.resetModules();
20
- });
21
-
22
- describe("when request retry attribute is set to false", () => {
23
- it("should not retry request on failure", async () => {
24
- // Todo
25
- });
26
- });
27
- describe("when request retry attribute is set to true", () => {
28
- it("should retry request once", async () => {
29
- // Todo
30
- });
31
- it("should retry request twice", async () => {
32
- // Todo
33
- });
34
- it("should trigger retries with the config interval", async () => {
35
- // Todo
36
- });
37
- });
38
- });