@hyper-fetch/react 9.6.0 → 9.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/__tests__/features/helpers/use-request-events/use-request-events.async-mapper.spec.ts +243 -0
  2. package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
  3. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
  4. package/__tests__/features/helpers/utils.spec.ts +127 -0
  5. package/__tests__/features/provider/provider.config.spec.tsx +172 -0
  6. package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
  7. package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
  8. package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
  9. package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
  10. package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
  11. package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
  12. package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +6 -3
  13. package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +72 -80
  14. package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
  15. package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
  16. package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
  17. package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
  18. package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
  19. package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
  20. package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
  21. package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
  22. package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +36 -13
  23. package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
  24. package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
  25. package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
  26. package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
  27. package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
  28. package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
  29. package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
  30. package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
  31. package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +11 -2
  32. package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
  33. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
  34. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
  35. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
  36. package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +19 -9
  37. package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
  38. package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
  39. package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
  40. package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
  41. package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
  42. package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
  43. package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
  44. package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
  45. package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
  46. package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
  47. package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
  48. package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
  49. package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +2 -1
  50. package/__tests__/features/use-submit/use-submit.debounce.spec.ts +100 -124
  51. package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
  52. package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
  53. package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
  54. package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +8 -1
  55. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  56. package/__tests__/features/use-submit/use-submit.retry.spec.ts +51 -35
  57. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  58. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  59. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  60. package/__tests__/features/use-submit/use-submit.unmount.spec.ts +2 -1
  61. package/__tests__/utils/gate.utils.ts +103 -0
  62. package/__tests__/utils/gated-client.utils.ts +158 -0
  63. package/__tests__/utils/helpers.utils.ts +19 -0
  64. package/__tests__/utils/use-queue.utils.ts +8 -4
  65. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  66. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  67. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  68. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  69. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  70. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  71. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  72. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  73. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  74. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  75. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  76. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  77. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  78. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  79. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  80. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  81. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  82. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  83. package/dist/index.mjs +633 -347
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/provider/provider.d.ts.map +1 -1
  86. package/package.json +1 -1
  87. package/src/helpers/use-request-events/use-request-events.hooks.ts +147 -32
  88. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  89. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  90. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  91. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  92. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  93. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  94. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  95. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  96. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  97. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  98. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  99. package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
  100. package/src/provider/provider.tsx +9 -1
  101. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  102. 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,27 +112,47 @@ 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 requestClone = request.clone(submitOptions as any) as unknown as RequestType;
155
+
131
156
  const triggerRequest = () => {
132
157
  addCacheDataListener(requestClone);
133
158
 
@@ -135,9 +160,19 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
135
160
  dispatcherType: "submit",
136
161
  ...(submitOptions as RequestSendOptionsType<RequestType>),
137
162
  onBeforeSent: (data) => {
163
+ // Deduplicated submit joins the request which is already in flight and shares its id.
164
+ // We keep a single set of listeners for it, so the callbacks fire once per response.
165
+ removeLifecycleListener(data.requestId);
138
166
  addLifecycleListeners(requestClone, data.requestId, data.mutationContext);
139
167
  submitOptions?.onBeforeSent?.(data);
140
168
  },
169
+ onResponse: (data) => {
170
+ // This is the final response (retries and waiting for the network are over) and our listeners already
171
+ // handled it. Dispatcher does not announce the removal of every request (e.g. the canceled ones),
172
+ // so we release the listeners here to not leak them.
173
+ removeLifecycleListener(data.requestId);
174
+ submitOptions?.onResponse?.(data);
175
+ },
141
176
  };
142
177
 
143
178
  return sendRequest(requestClone, configuration);
@@ -159,20 +194,33 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
159
194
  >,
160
195
  ) => {
161
196
  // Trigger previous awaiting calls to resolve together in bounced batches
162
- bouncedResolve(value);
197
+ bouncedResolve?.(value);
163
198
  resolve(value);
164
199
  };
165
200
 
201
+ let isTriggered = false;
202
+
166
203
  // Start bounce
167
204
  bounceFunction(async () => {
205
+ isTriggered = true;
168
206
  // We will always resolve previous calls as we stack the callbacks together until bounce function trigger
169
207
  const callback = bounceResolver.current;
170
208
  // Clean bounce resolvers to start the new stack
171
- bounceResolver.current = () => null;
209
+ bounceResolver.current = null;
172
210
 
173
211
  const value = await triggerRequest();
174
- callback(value);
212
+ callback?.(value);
175
213
  });
214
+
215
+ // Throttle without the trailing timeout drops the calls made during the interval - nothing will trigger them
216
+ if (!isTriggered && !bounceData.active) {
217
+ resolveBouncedCalls("Request was not sent. Submit call got dropped by the throttle");
218
+ }
219
+
220
+ // Throttle does not notify about the call it holds, so the returned bounce state would stay outdated
221
+ if (bounceData.active !== isBounceActive) {
222
+ forceUpdate();
223
+ }
176
224
  } else {
177
225
  const value = await triggerRequest();
178
226
  resolve(value);
@@ -187,35 +235,97 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
187
235
  // Invalidation
188
236
  // ******************
189
237
 
190
- const refetch = () => {
238
+ const handleRefetch = () => {
191
239
  cache.invalidate(request);
192
240
  };
193
241
 
194
242
  // ******************
195
- // Misc
243
+ // Stable methods
244
+ // ******************
245
+
246
+ // The returned methods keep their identity between renders (safe to use in the dependency arrays)
247
+ // and always work with the request and options from the latest render
248
+ const latest = useRef({ handleSubmit, handleRefetch, resolveBouncedCalls });
249
+ latest.current = { handleSubmit, handleRefetch, resolveBouncedCalls };
250
+
251
+ const submit = useCallback(
252
+ ((submitOptions?: RequestSendOptionsType<RequestType>) =>
253
+ (latest.current.handleSubmit as (options?: RequestSendOptionsType<RequestType>) => unknown)(
254
+ submitOptions,
255
+ )) as unknown as RequestSendType<RequestType>,
256
+ [],
257
+ );
258
+
259
+ const refetch = useCallback(() => latest.current.handleRefetch(), []);
260
+
261
+ // ******************
262
+ // Bounce
196
263
  // ******************
197
264
 
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,
265
+ const resetBounce = () => {
266
+ const wasActive = bounceData.active;
267
+ bounceData.reset();
268
+ resolveBouncedCalls("Request was not sent. Bounce got reset before triggering the request");
269
+ // Reset does not notify about the change on its own
270
+ if (wasActive) {
271
+ forceUpdate();
272
+ }
208
273
  };
209
274
 
275
+ // ******************
276
+ // Misc
277
+ // ******************
278
+
279
+ const handlers = useMemo(() => {
280
+ /**
281
+ * Callbacks run inside of the request lifecycle. Error thrown by one of them would break it - the request
282
+ * would never finish and it would block the queue. Such error is thrown outside of the lifecycle instead,
283
+ * the same way as the errors of every other callback, listener and plugin.
284
+ */
285
+ const protect = <Args extends unknown[]>(callback: (...args: Args) => void | Promise<void>) => {
286
+ return (...args: Args): void => {
287
+ runUserCode(() => {
288
+ callback(...args);
289
+ });
290
+ };
291
+ };
292
+
293
+ return {
294
+ onSubmitSuccess: (callback: Parameters<typeof callbacks.onSuccess>[0]) => callbacks.onSuccess(protect(callback)),
295
+ onSubmitError: (callback: Parameters<typeof callbacks.onError>[0]) => callbacks.onError(protect(callback)),
296
+ onSubmitFinished: (callback: Parameters<typeof callbacks.onFinished>[0]) =>
297
+ callbacks.onFinished(protect(callback)),
298
+ onSubmitRequestStart: (callback: Parameters<typeof callbacks.onRequestStart>[0]) =>
299
+ callbacks.onRequestStart(protect(callback)),
300
+ onSubmitResponseStart: (callback: Parameters<typeof callbacks.onResponseStart>[0]) =>
301
+ callbacks.onResponseStart(protect(callback)),
302
+ onSubmitDownloadProgress: (callback: Parameters<typeof callbacks.onDownloadProgress>[0]) =>
303
+ callbacks.onDownloadProgress(protect(callback) as typeof callback),
304
+ onSubmitUploadProgress: (callback: Parameters<typeof callbacks.onUploadProgress>[0]) =>
305
+ callbacks.onUploadProgress(protect(callback) as typeof callback),
306
+ onSubmitOfflineError: (callback: Parameters<typeof callbacks.onOfflineError>[0]) =>
307
+ callbacks.onOfflineError(protect(callback)),
308
+ onSubmitAbort: (callback: Parameters<typeof callbacks.onAbort>[0]) => callbacks.onAbort(protect(callback)),
309
+ };
310
+ }, [callbacks]);
311
+
210
312
  // ******************
211
313
  // Lifecycle
212
314
  // ******************
213
315
 
214
316
  // 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
317
+ // so a mount-once guard would leave the hook without the cache subscription.
318
+ // When the request changes, we follow the data of the new one.
216
319
  useEffect(() => {
217
320
  addCacheDataListener(request);
218
321
  // eslint-disable-next-line react-hooks/exhaustive-deps
322
+ }, [request.cacheKey, request.queryKey, request.scope]);
323
+
324
+ // Bounce timers get cleared on unmount, so the waiting submit calls would never get resolved
325
+ useEffect(() => {
326
+ return () => {
327
+ latest.current.resolveBouncedCalls("Request was not sent. Hook got unmounted before triggering the request");
328
+ };
219
329
  }, []);
220
330
 
221
331
  const setSubmitRenderKey = (key: string) => {
@@ -236,7 +346,7 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
236
346
 
237
347
  return createTrackedProxy(
238
348
  {
239
- submit: handleSubmit,
349
+ submit,
240
350
  data: state.data,
241
351
  error: state.error,
242
352
  submitting: state.loading,
@@ -249,7 +359,7 @@ export const useSubmit = <RequestType extends RequestInstance, TSelected = Extra
249
359
  abort: callbacks.abort,
250
360
  ...actions,
251
361
  ...handlers,
252
- bounce: getBounceData(bounceData),
362
+ bounce: { ...getBounceData(bounceData), reset: resetBounce },
253
363
  refetch,
254
364
  },
255
365
  trackedKeys,
@@ -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
- });