@hyper-fetch/react 9.6.0 → 9.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/helpers/use-request-events/use-request-events.async-mapper.spec.ts +243 -0
- package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
- package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
- package/__tests__/features/helpers/utils.spec.ts +127 -0
- package/__tests__/features/provider/provider.config.spec.tsx +172 -0
- package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
- package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
- package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
- package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
- package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
- package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
- package/__tests__/features/use-fetch/use-fetch.cancel.spec.ts +6 -3
- package/__tests__/features/use-fetch/use-fetch.debounce.spec.ts +72 -80
- package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
- package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
- package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
- package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
- package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
- package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
- package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
- package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
- package/__tests__/features/use-fetch/use-fetch.refresh.spec.ts +36 -13
- package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
- package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
- package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
- package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
- package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
- package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
- package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
- package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
- package/__tests__/features/use-fetch/use-fetch.utils.spec.ts +11 -2
- package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
- package/__tests__/features/use-is-fetching/use-is-fetching.base.spec.tsx +19 -9
- package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
- package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
- package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
- package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
- package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
- package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
- package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
- package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
- package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
- package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
- package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
- package/__tests__/features/use-submit/use-submit.concurrency.spec.ts +2 -1
- package/__tests__/features/use-submit/use-submit.debounce.spec.ts +100 -124
- package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
- package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
- package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
- package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +8 -1
- package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
- package/__tests__/features/use-submit/use-submit.retry.spec.ts +51 -35
- package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
- package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
- package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
- package/__tests__/features/use-submit/use-submit.unmount.spec.ts +2 -1
- package/__tests__/utils/gate.utils.ts +103 -0
- package/__tests__/utils/gated-client.utils.ts +158 -0
- package/__tests__/utils/helpers.utils.ts +19 -0
- package/__tests__/utils/use-queue.utils.ts +8 -4
- package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
- package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
- package/dist/index.mjs +633 -347
- package/dist/index.mjs.map +1 -1
- package/dist/provider/provider.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +147 -32
- package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
- package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
- package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
- package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
- package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
- package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
- package/src/provider/provider.tsx +9 -1
- package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
- package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { useDidUpdate } from "@better-hooks/lifecycle";
|
|
2
1
|
import { useDebounce, useThrottle } from "@better-hooks/performance";
|
|
3
2
|
import type {
|
|
4
3
|
ExtractErrorType,
|
|
@@ -209,17 +208,39 @@ export const useInfiniteFetch = <
|
|
|
209
208
|
}
|
|
210
209
|
|
|
211
210
|
if (bounce && previous && previous !== store && !store.hasPages()) {
|
|
212
|
-
bounceFunction(() =>
|
|
211
|
+
bounceFunction(() => {
|
|
212
|
+
// The list could have been left for another one, or disabled, before the bounce settled
|
|
213
|
+
if (mountedStore.current === store && !latest.current.disabled) {
|
|
214
|
+
store.start({ revalidate: latest.current.revalidate });
|
|
215
|
+
}
|
|
216
|
+
});
|
|
213
217
|
} else {
|
|
214
218
|
store.start({ revalidate });
|
|
215
219
|
}
|
|
216
220
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
217
221
|
}, [store, disabled]);
|
|
218
222
|
|
|
219
|
-
|
|
220
|
-
if (
|
|
223
|
+
useEffect(() => {
|
|
224
|
+
if (disabled) {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
return store.enable();
|
|
228
|
+
}, [store, disabled]);
|
|
229
|
+
|
|
230
|
+
// Effects run again in StrictMode and when a hidden list is shown - only changed values are a reason to refetch
|
|
231
|
+
const usedDependencies = useRef(dependencies);
|
|
232
|
+
|
|
233
|
+
useEffect(() => {
|
|
234
|
+
const previous = usedDependencies.current;
|
|
235
|
+
usedDependencies.current = dependencies;
|
|
236
|
+
|
|
237
|
+
const hasChanged =
|
|
238
|
+
previous.length !== dependencies.length ||
|
|
239
|
+
previous.some((value, index) => !Object.is(value, dependencies[index]));
|
|
240
|
+
if (hasChanged && !disabled) {
|
|
221
241
|
store.refetch();
|
|
222
242
|
}
|
|
243
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
223
244
|
}, dependencies);
|
|
224
245
|
|
|
225
246
|
useEffect(() => {
|
|
@@ -290,23 +311,6 @@ export const useInfiniteFetch = <
|
|
|
290
311
|
throw store.start({ revalidate });
|
|
291
312
|
}
|
|
292
313
|
|
|
293
|
-
// ******************
|
|
294
|
-
// Error boundary
|
|
295
|
-
// ******************
|
|
296
|
-
|
|
297
|
-
if (throwOnError) {
|
|
298
|
-
usedKeys.add("error");
|
|
299
|
-
usedKeys.add("isFetching");
|
|
300
|
-
|
|
301
|
-
const error = snapshot.error as ExtractErrorType<R> | null;
|
|
302
|
-
const shouldThrow = typeof throwOnError === "function" ? !!error && throwOnError(error) : !!error;
|
|
303
|
-
|
|
304
|
-
if (shouldThrow && !snapshot.isFetching) {
|
|
305
|
-
store.evictSoon();
|
|
306
|
-
throw error;
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
314
|
// ******************
|
|
311
315
|
// Items
|
|
312
316
|
// ******************
|
|
@@ -323,11 +327,36 @@ export const useInfiniteFetch = <
|
|
|
323
327
|
|
|
324
328
|
const selectedRef = useRef<unknown>(null);
|
|
325
329
|
let items: unknown = uniqueItems;
|
|
330
|
+
let selectError: unknown = null;
|
|
326
331
|
|
|
327
332
|
if (select) {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
333
|
+
try {
|
|
334
|
+
const selected = select({ items: uniqueItems as PaginationItem<R, P>[], pages: list.data as any[] });
|
|
335
|
+
items = structuralSharing ? replaceEqualDeep(selectedRef.current, selected) : selected;
|
|
336
|
+
selectedRef.current = items;
|
|
337
|
+
} catch (error) {
|
|
338
|
+
// Like in TanStack Query, a failing select is the error of the list and the last selected value stays
|
|
339
|
+
selectError = error;
|
|
340
|
+
items = selectedRef.current;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const error = (selectError ?? snapshot.error) as ExtractErrorType<R> | null;
|
|
345
|
+
|
|
346
|
+
// ******************
|
|
347
|
+
// Error boundary
|
|
348
|
+
// ******************
|
|
349
|
+
|
|
350
|
+
if (throwOnError) {
|
|
351
|
+
usedKeys.add("error");
|
|
352
|
+
usedKeys.add("isFetching");
|
|
353
|
+
|
|
354
|
+
const shouldThrow = typeof throwOnError === "function" ? !!error && throwOnError(error) : !!error;
|
|
355
|
+
|
|
356
|
+
if (shouldThrow && !snapshot.isFetching) {
|
|
357
|
+
store.evictSoon();
|
|
358
|
+
throw error;
|
|
359
|
+
}
|
|
331
360
|
}
|
|
332
361
|
|
|
333
362
|
// ******************
|
|
@@ -376,10 +405,10 @@ export const useInfiniteFetch = <
|
|
|
376
405
|
isFetchNextPageError: snapshot.isFetchNextPageError,
|
|
377
406
|
isFetchPreviousPageError: snapshot.isFetchPreviousPageError,
|
|
378
407
|
isPreviousData,
|
|
379
|
-
error
|
|
408
|
+
error,
|
|
380
409
|
status: snapshot.status,
|
|
381
410
|
extra: snapshot.extra,
|
|
382
|
-
success: snapshot.success,
|
|
411
|
+
success: !selectError && snapshot.success,
|
|
383
412
|
bounce: getBounceData(bounceData),
|
|
384
413
|
...actions,
|
|
385
414
|
},
|
|
@@ -1,10 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
CacheValueType,
|
|
3
|
-
ClientInstance,
|
|
4
|
-
PaginationConfig,
|
|
5
|
-
PaginationPageContext,
|
|
6
|
-
RequestInstance,
|
|
7
|
-
} from "@hyper-fetch/core";
|
|
1
|
+
import type { CacheValueType, PaginationConfig, PaginationPageContext, RequestInstance } from "@hyper-fetch/core";
|
|
8
2
|
import {
|
|
9
3
|
getCachedPages,
|
|
10
4
|
getHasNextPage,
|
|
@@ -33,25 +27,11 @@ import type {
|
|
|
33
27
|
OperationKind,
|
|
34
28
|
} from "./use-infinite-fetch.store.types";
|
|
35
29
|
import type { InfinitePageEvent } from "./use-infinite-fetch.types";
|
|
30
|
+
import { getStores, isSameSnapshot } from "./use-infinite-fetch.utils";
|
|
36
31
|
|
|
37
32
|
// Render and commit are separate steps, a store waits this long for the component that created it
|
|
38
33
|
const unusedStoreTime = 1000;
|
|
39
34
|
|
|
40
|
-
const stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();
|
|
41
|
-
|
|
42
|
-
const getStores = (client: ClientInstance) => {
|
|
43
|
-
let clientStores = stores.get(client);
|
|
44
|
-
if (!clientStores) {
|
|
45
|
-
clientStores = new Map();
|
|
46
|
-
stores.set(client, clientStores);
|
|
47
|
-
}
|
|
48
|
-
return clientStores;
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
const isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {
|
|
52
|
-
return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);
|
|
53
|
-
};
|
|
54
|
-
|
|
55
35
|
/**
|
|
56
36
|
* State of a single list. Hooks showing the same list share one store, so they stay in sync and never request
|
|
57
37
|
* the same page twice. Pages are ordinary requests under their own cache keys - nothing extra is stored.
|
|
@@ -71,6 +51,7 @@ export class InfiniteStore {
|
|
|
71
51
|
private refetchedKeys = new Set<string>();
|
|
72
52
|
private unmountCacheListeners: VoidFunction | null = null;
|
|
73
53
|
private unusedTimer: ReturnType<typeof setTimeout> | null = null;
|
|
54
|
+
private enabledHooks = 0;
|
|
74
55
|
private started = false;
|
|
75
56
|
private settled = false;
|
|
76
57
|
private firstFetch: Promise<any> = Promise.resolve(null);
|
|
@@ -120,6 +101,14 @@ export class InfiniteStore {
|
|
|
120
101
|
};
|
|
121
102
|
};
|
|
122
103
|
|
|
104
|
+
/** Counts the hooks allowed to fetch - changes of the cache refetch the list only for them */
|
|
105
|
+
enable = () => {
|
|
106
|
+
this.enabledHooks += 1;
|
|
107
|
+
return () => {
|
|
108
|
+
this.enabledHooks -= 1;
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
|
|
123
112
|
/** Callbacks can capture values of the latest render */
|
|
124
113
|
setPagination = (pagination: PaginationConfig) => {
|
|
125
114
|
this.options.pagination = pagination;
|
|
@@ -136,6 +125,11 @@ export class InfiniteStore {
|
|
|
136
125
|
*/
|
|
137
126
|
start = ({ revalidate }: { revalidate?: boolean } = {}) => {
|
|
138
127
|
if (this.started) {
|
|
128
|
+
// A hook joining a list already on screen, or coming back to it, checks the loaded pages like a new mount
|
|
129
|
+
const isIdle = !this.running && this.queue.length === 0;
|
|
130
|
+
if (isIdle && this.pages.length > 0 && (revalidate || this.getHasStalePages())) {
|
|
131
|
+
this.revalidate();
|
|
132
|
+
}
|
|
139
133
|
return this.firstFetch;
|
|
140
134
|
}
|
|
141
135
|
this.started = true;
|
|
@@ -400,13 +394,20 @@ export class InfiniteStore {
|
|
|
400
394
|
return null;
|
|
401
395
|
}
|
|
402
396
|
|
|
403
|
-
const
|
|
404
|
-
const last = failed ?? results.findLast(Boolean);
|
|
405
|
-
|
|
406
|
-
this.pages = current.map((page, index) => {
|
|
397
|
+
const pages = current.map((page, index) => {
|
|
407
398
|
const fetched = results[index];
|
|
408
399
|
return fetched?.response.success ? this.createPage(fetched) : page;
|
|
409
400
|
});
|
|
401
|
+
// The list can be shorter than before. Pages after its new end are gone, whatever their requests returned.
|
|
402
|
+
const end = pages.findIndex((page, index) => {
|
|
403
|
+
return results[index]?.response.success && !getHasNextPage(this.getContext(page, pages.slice(0, index + 1)));
|
|
404
|
+
});
|
|
405
|
+
const length = end === -1 ? pages.length : end + 1;
|
|
406
|
+
const kept = results.slice(0, length);
|
|
407
|
+
const failed = kept.find((fetched) => fetched && !fetched.response.success);
|
|
408
|
+
const last = failed ?? kept.findLast(Boolean);
|
|
409
|
+
|
|
410
|
+
this.pages = pages.slice(0, length);
|
|
410
411
|
if (last) {
|
|
411
412
|
this.setResult(last.response);
|
|
412
413
|
}
|
|
@@ -522,8 +523,10 @@ export class InfiniteStore {
|
|
|
522
523
|
};
|
|
523
524
|
|
|
524
525
|
private getHasStalePages = () => {
|
|
525
|
-
return this.pages.some((
|
|
526
|
-
|
|
526
|
+
return this.pages.some(({ request, responseTimestamp }) => {
|
|
527
|
+
// Pages of requests without cache are kept only here
|
|
528
|
+
const kept = request.cache ? null : { staleTime: request.staleTime, responseTimestamp };
|
|
529
|
+
const value = this.readValue(request) ?? kept;
|
|
527
530
|
return !value || isStaleCacheData(value.staleTime, value.responseTimestamp);
|
|
528
531
|
});
|
|
529
532
|
};
|
|
@@ -616,6 +619,9 @@ export class InfiniteStore {
|
|
|
616
619
|
};
|
|
617
620
|
|
|
618
621
|
private setResult = (response: any) => {
|
|
622
|
+
// Like the flags of TanStack Query, these describe the last fetch only - next and previous set theirs after this
|
|
623
|
+
this.nextPageError = false;
|
|
624
|
+
this.previousPageError = false;
|
|
619
625
|
this.result = {
|
|
620
626
|
error: response.success ? null : response.error,
|
|
621
627
|
status: response.status,
|
|
@@ -709,7 +715,7 @@ export class InfiniteStore {
|
|
|
709
715
|
this.hasInvalidation = true;
|
|
710
716
|
queueMicrotask(() => {
|
|
711
717
|
this.hasInvalidation = false;
|
|
712
|
-
if (this.
|
|
718
|
+
if (this.enabledHooks > 0) {
|
|
713
719
|
this.refetch();
|
|
714
720
|
}
|
|
715
721
|
});
|
|
@@ -45,6 +45,8 @@ export type UseInfiniteFetchOptionsType<
|
|
|
45
45
|
maxPages?: number;
|
|
46
46
|
/**
|
|
47
47
|
* Transforms the list used by the component. The cache stays shared with other hooks.
|
|
48
|
+
* When it throws, the error is returned in `error` (or thrown with `throwOnError`) and `items` keeps
|
|
49
|
+
* the last selected value.
|
|
48
50
|
*/
|
|
49
51
|
select?: (context: { items: PaginationItem<R, P>[]; pages: ExtractResponseType<R>[] }) => TSelected;
|
|
50
52
|
/**
|
|
@@ -155,13 +157,13 @@ export type UseInfiniteFetchReturnType<
|
|
|
155
157
|
isRefetching: boolean;
|
|
156
158
|
isFetchingNextPage: boolean;
|
|
157
159
|
isFetchingPreviousPage: boolean;
|
|
158
|
-
/**
|
|
160
|
+
/** The last fetch of the list was a failed attempt of fetching the next page */
|
|
159
161
|
isFetchNextPageError: boolean;
|
|
160
|
-
/**
|
|
162
|
+
/** The last fetch of the list was a failed attempt of fetching the previous page */
|
|
161
163
|
isFetchPreviousPageError: boolean;
|
|
162
164
|
/** The list on screen belongs to the previous request, the new one is still loading */
|
|
163
165
|
isPreviousData: boolean;
|
|
164
|
-
/** Error of the last fetch */
|
|
166
|
+
/** Error of the last fetch, or the error thrown by `select` */
|
|
165
167
|
error: ExtractErrorType<R> | null;
|
|
166
168
|
/** Status of the last response */
|
|
167
169
|
status: ExtractAdapterStatusType<ExtractAdapterType<R>> | null;
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import type { RequestInstance } from "@hyper-fetch/core";
|
|
1
|
+
import type { ClientInstance, RequestInstance } from "@hyper-fetch/core";
|
|
2
|
+
|
|
3
|
+
import type { InfiniteStore } from "./use-infinite-fetch.store";
|
|
4
|
+
import type { InfiniteSnapshot } from "./use-infinite-fetch.store.types";
|
|
2
5
|
|
|
3
6
|
/**
|
|
4
7
|
* Identity of a list. Everything describing the request takes part in it, so a changed filter, sort, page size
|
|
@@ -42,3 +45,24 @@ export const getShouldKeepPreviousList = (
|
|
|
42
45
|
}
|
|
43
46
|
return mode === "preserve";
|
|
44
47
|
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Tells whether nothing changed between two states of a list, so nobody has to be notified
|
|
51
|
+
*/
|
|
52
|
+
export const isSameSnapshot = (a: InfiniteSnapshot, b: InfiniteSnapshot) => {
|
|
53
|
+
return (Object.keys(a) as (keyof InfiniteSnapshot)[]).every((key) => a[key] === b[key]);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const stores = new WeakMap<ClientInstance, Map<string, InfiniteStore>>();
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Stores of the lists shown with the client, by the key of the list
|
|
60
|
+
*/
|
|
61
|
+
export const getStores = (client: ClientInstance) => {
|
|
62
|
+
let clientStores = stores.get(client);
|
|
63
|
+
if (!clientStores) {
|
|
64
|
+
clientStores = new Map();
|
|
65
|
+
stores.set(client, clientStores);
|
|
66
|
+
}
|
|
67
|
+
return clientStores;
|
|
68
|
+
};
|
|
@@ -116,7 +116,8 @@ export const useListener = <
|
|
|
116
116
|
listen();
|
|
117
117
|
},
|
|
118
118
|
// Topic already contains resolved params. Delivery presets compare by value, custom strategies by identity.
|
|
119
|
-
|
|
119
|
+
// The socket is a dependency too - the same topic on another socket is a different subscription.
|
|
120
|
+
[listener.socket, listener.topic, JSON.stringify(listener.options), getDeliveryKey(listener.delivery)],
|
|
120
121
|
true,
|
|
121
122
|
);
|
|
122
123
|
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {
|
|
2
|
+
ProgressType,
|
|
3
|
+
RequestInstance,
|
|
4
|
+
ResolvedQueueItemType,
|
|
5
|
+
QueueDataType,
|
|
6
|
+
QueueItemType,
|
|
7
|
+
} from "@hyper-fetch/core";
|
|
2
8
|
import { Request, getRequestDispatcher, scopeKey } from "@hyper-fetch/core";
|
|
3
9
|
import type { UseQueueOptionsType, QueueRequest, UseQueueReturnType } from "hooks/use-queue";
|
|
4
10
|
import { useQueueDefaultOptions } from "hooks/use-queue";
|
|
@@ -14,6 +20,15 @@ const canUpdate = (
|
|
|
14
20
|
return true;
|
|
15
21
|
};
|
|
16
22
|
|
|
23
|
+
const getInitialProgress = (): ProgressType => ({
|
|
24
|
+
progress: 0,
|
|
25
|
+
timeLeft: 0,
|
|
26
|
+
sizeLeft: 0,
|
|
27
|
+
total: 0,
|
|
28
|
+
loaded: 0,
|
|
29
|
+
startTimestamp: 0,
|
|
30
|
+
});
|
|
31
|
+
|
|
17
32
|
/**
|
|
18
33
|
* This hook allows you to monitor and control dispatcher request queues for a given request,
|
|
19
34
|
* including starting, stopping, pausing, and inspecting pending/in-flight items.
|
|
@@ -40,9 +55,6 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
40
55
|
|
|
41
56
|
const [dispatcher] = getRequestDispatcher(request, dispatcherType);
|
|
42
57
|
|
|
43
|
-
const [stopped, setStopped] = useState(false);
|
|
44
|
-
const [requests, setRequests] = useState<QueueRequest<Request>[]>([]);
|
|
45
|
-
|
|
46
58
|
// ******************
|
|
47
59
|
// Mapping
|
|
48
60
|
// ******************
|
|
@@ -50,47 +62,56 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
50
62
|
const createRequestsArray = useCallback(
|
|
51
63
|
(
|
|
52
64
|
queueElements: ResolvedQueueItemType<Request>[],
|
|
53
|
-
prevRequests
|
|
65
|
+
prevRequests: QueueRequest<Request>[] = [],
|
|
54
66
|
): QueueRequest<Request>[] => {
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),
|
|
83
|
-
}));
|
|
84
|
-
|
|
85
|
-
if (keepFinishedRequests && prevRequests) {
|
|
86
|
-
return [...prevRequests, ...newRequests];
|
|
67
|
+
const previous = new Map(prevRequests.map((el) => [el.requestId, el]));
|
|
68
|
+
|
|
69
|
+
// The list mirrors the dispatcher queue - requests we already track keep their local state
|
|
70
|
+
// (progress and result flags) and get the latest queue values (stopped, retries, resolved)
|
|
71
|
+
const current = new Map(
|
|
72
|
+
queueElements.map((req) => {
|
|
73
|
+
const tracked = previous.get(req.requestId);
|
|
74
|
+
const item: QueueRequest<Request> = tracked
|
|
75
|
+
? { ...tracked, ...req }
|
|
76
|
+
: {
|
|
77
|
+
failed: false,
|
|
78
|
+
canceled: false,
|
|
79
|
+
removed: false,
|
|
80
|
+
success: false,
|
|
81
|
+
...req,
|
|
82
|
+
downloading: getInitialProgress(),
|
|
83
|
+
uploading: getInitialProgress(),
|
|
84
|
+
stopRequest: () => dispatcher.stopRequest(queryKey, req.requestId),
|
|
85
|
+
startRequest: () => dispatcher.startRequest(queryKey, req.requestId),
|
|
86
|
+
deleteRequest: () => dispatcher.delete(queryKey, req.requestId, abortKey),
|
|
87
|
+
};
|
|
88
|
+
return [req.requestId, item];
|
|
89
|
+
}),
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
if (!keepFinishedRequests) {
|
|
93
|
+
return [...current.values()];
|
|
87
94
|
}
|
|
88
95
|
|
|
89
|
-
|
|
96
|
+
// Requests that left the queue keep their place, new ones are added at the end
|
|
97
|
+
const kept = prevRequests.map((el) => current.get(el.requestId) || el);
|
|
98
|
+
const added = [...current.values()].filter((el) => !previous.has(el.requestId));
|
|
99
|
+
|
|
100
|
+
return [...kept, ...added];
|
|
90
101
|
},
|
|
91
102
|
[abortKey, dispatcher, queryKey, keepFinishedRequests],
|
|
92
103
|
);
|
|
93
104
|
|
|
105
|
+
// ******************
|
|
106
|
+
// State
|
|
107
|
+
// ******************
|
|
108
|
+
|
|
109
|
+
// Read the queue right away, so the first render already shows its real state
|
|
110
|
+
const [stopped, setStopped] = useState(() => dispatcher.getQueue<Request>(queryKey).stopped);
|
|
111
|
+
const [requests, setRequests] = useState<QueueRequest<Request>[]>(() =>
|
|
112
|
+
createRequestsArray(dispatcher.getQueue<Request>(queryKey).requests),
|
|
113
|
+
);
|
|
114
|
+
|
|
94
115
|
const mergePayloadType = useCallback((requestId: string, data: Partial<QueueRequest<Request>>) => {
|
|
95
116
|
setRequests((prev) =>
|
|
96
117
|
prev.map((el) => {
|
|
@@ -102,10 +123,6 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
102
123
|
);
|
|
103
124
|
}, []);
|
|
104
125
|
|
|
105
|
-
// ******************
|
|
106
|
-
// State
|
|
107
|
-
// ******************
|
|
108
|
-
|
|
109
126
|
const getInitialState = () => {
|
|
110
127
|
const requestQueue = dispatcher.getQueue<Request>(queryKey);
|
|
111
128
|
|
|
@@ -141,16 +158,32 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
141
158
|
const unmountChange = dispatcher.events.onQueueChangeByKey<Request>(queryKey, updateQueueState);
|
|
142
159
|
const unmountStatus = dispatcher.events.onQueueStatusChangeByKey<Request>(queryKey, updateQueueState);
|
|
143
160
|
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
161
|
+
const unmountResponse = requestManager.events.onResponse(({ requestId, response, details }) => {
|
|
162
|
+
setRequests((prev) =>
|
|
163
|
+
prev.map((el) => {
|
|
164
|
+
if (el.requestId !== requestId) {
|
|
165
|
+
return el;
|
|
166
|
+
}
|
|
167
|
+
if (response.success) {
|
|
168
|
+
return { ...el, success: true };
|
|
169
|
+
}
|
|
170
|
+
// The request is not done yet when it will be sent again - after the retry time,
|
|
171
|
+
// once the queue gets started again or when the network connection is back
|
|
172
|
+
const isRepeated =
|
|
173
|
+
!!details?.willRetry || !!details?.isCanceled || (!!details?.isOffline && !!el.request.offline);
|
|
174
|
+
return isRepeated ? el : { ...el, failed: true };
|
|
175
|
+
}),
|
|
176
|
+
);
|
|
150
177
|
});
|
|
151
178
|
const unmountCanceled = requestManager.events.onAbort(({ requestId }) => {
|
|
152
179
|
setRequests((prev) => prev.map((el) => (el.requestId === requestId ? { ...el, canceled: true } : el)));
|
|
153
180
|
});
|
|
181
|
+
// Canceled request can be sent again - for example after starting the stopped queue
|
|
182
|
+
const unmountStarted = requestManager.events.onRequestStart(({ requestId }) => {
|
|
183
|
+
setRequests((prev) =>
|
|
184
|
+
prev.map((el) => (el.requestId === requestId && el.canceled ? { ...el, canceled: false } : el)),
|
|
185
|
+
);
|
|
186
|
+
});
|
|
154
187
|
|
|
155
188
|
const unmountRemoved = requestManager.events.onRemove(({ requestId }) => {
|
|
156
189
|
setRequests((prev) =>
|
|
@@ -175,8 +208,9 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
175
208
|
unmountChange();
|
|
176
209
|
unmountDownload();
|
|
177
210
|
unmountUpload();
|
|
178
|
-
|
|
211
|
+
unmountResponse();
|
|
179
212
|
unmountCanceled();
|
|
213
|
+
unmountStarted();
|
|
180
214
|
unmountRemoved();
|
|
181
215
|
};
|
|
182
216
|
|
|
@@ -189,17 +223,8 @@ export const useQueue = <Request extends RequestInstance>(
|
|
|
189
223
|
|
|
190
224
|
useEffect(getInitialState, [createRequestsArray, dispatcher, queryKey]);
|
|
191
225
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
requests,
|
|
195
|
-
setRequests,
|
|
196
|
-
setStopped,
|
|
197
|
-
queryKey,
|
|
198
|
-
dispatcher.events,
|
|
199
|
-
requestManager.events,
|
|
200
|
-
updateQueueState,
|
|
201
|
-
mergePayloadType,
|
|
202
|
-
]);
|
|
226
|
+
// The handlers only use state updaters, so there is no need to subscribe again when the state changes
|
|
227
|
+
useEffect(mountEvents, [queryKey, dispatcher.events, requestManager.events, updateQueueState, mergePayloadType]);
|
|
203
228
|
|
|
204
229
|
return {
|
|
205
230
|
stopped,
|