@tanstack/preact-pacer 0.22.1 → 0.24.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.
- package/README.md +17 -2
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +2 -5
- package/dist/async-batcher/useAsyncBatchedCallback.js +1 -2
- package/dist/async-batcher/useAsyncBatcher.d.ts +4 -8
- package/dist/async-batcher/useAsyncBatcher.js +1 -3
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +6 -7
- package/dist/async-debouncer/useAsyncDebouncedCallback.js +5 -4
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +4 -7
- package/dist/async-debouncer/useAsyncDebouncer.js +1 -2
- package/dist/async-queuer/useAsyncQueuedState.d.ts +4 -7
- package/dist/async-queuer/useAsyncQueuedState.js +3 -4
- package/dist/async-queuer/useAsyncQueuer.d.ts +6 -9
- package/dist/async-queuer/useAsyncQueuer.js +3 -4
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +2 -5
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +1 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +4 -7
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +1 -2
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +7 -9
- package/dist/async-throttler/useAsyncThrottledCallback.js +6 -6
- package/dist/async-throttler/useAsyncThrottler.d.ts +4 -7
- package/dist/async-throttler/useAsyncThrottler.js +1 -2
- package/dist/batcher/useBatchedCallback.d.ts +2 -5
- package/dist/batcher/useBatchedCallback.js +1 -2
- package/dist/batcher/useBatcher.d.ts +6 -11
- package/dist/batcher/useBatcher.js +3 -6
- package/dist/debouncer/useDebouncedCallback.d.ts +2 -5
- package/dist/debouncer/useDebouncedCallback.js +1 -2
- package/dist/debouncer/useDebouncedState.d.ts +2 -5
- package/dist/debouncer/useDebouncedState.js +1 -2
- package/dist/debouncer/useDebouncedValue.d.ts +2 -5
- package/dist/debouncer/useDebouncedValue.js +1 -2
- package/dist/debouncer/useDebouncer.d.ts +4 -7
- package/dist/debouncer/useDebouncer.js +1 -2
- package/dist/provider/PacerProvider.d.ts +6 -13
- package/dist/provider/PacerProvider.js +1 -2
- package/dist/queuer/useQueuedState.d.ts +2 -5
- package/dist/queuer/useQueuedState.js +1 -2
- package/dist/queuer/useQueuedValue.d.ts +2 -5
- package/dist/queuer/useQueuedValue.js +1 -2
- package/dist/queuer/useQueuer.d.ts +4 -7
- package/dist/queuer/useQueuer.js +1 -2
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedCallback.js +1 -2
- package/dist/rate-limiter/useRateLimitedState.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedState.js +1 -2
- package/dist/rate-limiter/useRateLimitedValue.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedValue.js +1 -2
- package/dist/rate-limiter/useRateLimiter.d.ts +4 -7
- package/dist/rate-limiter/useRateLimiter.js +1 -2
- package/dist/throttler/useThrottledCallback.d.ts +2 -5
- package/dist/throttler/useThrottledCallback.js +1 -2
- package/dist/throttler/useThrottledState.d.ts +2 -5
- package/dist/throttler/useThrottledState.js +1 -2
- package/dist/throttler/useThrottledValue.d.ts +2 -5
- package/dist/throttler/useThrottledValue.js +1 -2
- package/dist/throttler/useThrottler.d.ts +4 -7
- package/dist/throttler/useThrottler.js +1 -2
- package/package.json +24 -72
- package/dist/async-batcher/index.cjs +0 -13
- package/dist/async-batcher/index.d.cts +0 -4
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +0 -51
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +0 -1
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +0 -44
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +0 -1
- package/dist/async-batcher/useAsyncBatcher.cjs +0 -217
- package/dist/async-batcher/useAsyncBatcher.cjs.map +0 -1
- package/dist/async-batcher/useAsyncBatcher.d.cts +0 -224
- package/dist/async-batcher/useAsyncBatcher.js.map +0 -1
- package/dist/async-debouncer/index.cjs +0 -13
- package/dist/async-debouncer/index.d.cts +0 -4
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +0 -50
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +0 -46
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncer.cjs +0 -195
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +0 -203
- package/dist/async-debouncer/useAsyncDebouncer.js.map +0 -1
- package/dist/async-queuer/index.cjs +0 -13
- package/dist/async-queuer/index.d.cts +0 -4
- package/dist/async-queuer/useAsyncQueuedState.cjs +0 -154
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +0 -1
- package/dist/async-queuer/useAsyncQueuedState.d.cts +0 -151
- package/dist/async-queuer/useAsyncQueuedState.js.map +0 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +0 -217
- package/dist/async-queuer/useAsyncQueuer.cjs.map +0 -1
- package/dist/async-queuer/useAsyncQueuer.d.cts +0 -224
- package/dist/async-queuer/useAsyncQueuer.js.map +0 -1
- package/dist/async-rate-limiter/index.cjs +0 -13
- package/dist/async-rate-limiter/index.d.cts +0 -4
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +0 -65
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +0 -61
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +0 -209
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +0 -220
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +0 -1
- package/dist/async-retryer/index.cjs +0 -9
- package/dist/async-retryer/index.d.cts +0 -1
- package/dist/async-throttler/index.cjs +0 -13
- package/dist/async-throttler/index.d.cts +0 -4
- package/dist/async-throttler/useAsyncThrottledCallback.cjs +0 -48
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +0 -1
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +0 -44
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +0 -1
- package/dist/async-throttler/useAsyncThrottler.cjs +0 -206
- package/dist/async-throttler/useAsyncThrottler.cjs.map +0 -1
- package/dist/async-throttler/useAsyncThrottler.d.cts +0 -214
- package/dist/async-throttler/useAsyncThrottler.js.map +0 -1
- package/dist/batcher/index.cjs +0 -13
- package/dist/batcher/index.d.cts +0 -4
- package/dist/batcher/useBatchedCallback.cjs +0 -47
- package/dist/batcher/useBatchedCallback.cjs.map +0 -1
- package/dist/batcher/useBatchedCallback.d.cts +0 -42
- package/dist/batcher/useBatchedCallback.js.map +0 -1
- package/dist/batcher/useBatcher.cjs +0 -165
- package/dist/batcher/useBatcher.cjs.map +0 -1
- package/dist/batcher/useBatcher.d.cts +0 -175
- package/dist/batcher/useBatcher.js.map +0 -1
- package/dist/debouncer/index.cjs +0 -17
- package/dist/debouncer/index.d.cts +0 -6
- package/dist/debouncer/useDebouncedCallback.cjs +0 -48
- package/dist/debouncer/useDebouncedCallback.cjs.map +0 -1
- package/dist/debouncer/useDebouncedCallback.d.cts +0 -44
- package/dist/debouncer/useDebouncedCallback.js.map +0 -1
- package/dist/debouncer/useDebouncedState.cjs +0 -89
- package/dist/debouncer/useDebouncedState.cjs.map +0 -1
- package/dist/debouncer/useDebouncedState.d.cts +0 -81
- package/dist/debouncer/useDebouncedState.js.map +0 -1
- package/dist/debouncer/useDebouncedValue.cjs +0 -96
- package/dist/debouncer/useDebouncedValue.cjs.map +0 -1
- package/dist/debouncer/useDebouncedValue.d.cts +0 -90
- package/dist/debouncer/useDebouncedValue.js.map +0 -1
- package/dist/debouncer/useDebouncer.cjs +0 -141
- package/dist/debouncer/useDebouncer.cjs.map +0 -1
- package/dist/debouncer/useDebouncer.d.cts +0 -152
- package/dist/debouncer/useDebouncer.js.map +0 -1
- package/dist/index.cjs +0 -67
- package/dist/index.d.cts +0 -30
- package/dist/provider/PacerProvider.cjs +0 -26
- package/dist/provider/PacerProvider.cjs.map +0 -1
- package/dist/provider/PacerProvider.d.cts +0 -33
- package/dist/provider/PacerProvider.js.map +0 -1
- package/dist/provider/index.cjs +0 -6
- package/dist/provider/index.d.cts +0 -2
- package/dist/queuer/index.cjs +0 -15
- package/dist/queuer/index.d.cts +0 -5
- package/dist/queuer/useQueuedState.cjs +0 -129
- package/dist/queuer/useQueuedState.cjs.map +0 -1
- package/dist/queuer/useQueuedState.d.cts +0 -122
- package/dist/queuer/useQueuedState.js.map +0 -1
- package/dist/queuer/useQueuedValue.cjs +0 -115
- package/dist/queuer/useQueuedValue.cjs.map +0 -1
- package/dist/queuer/useQueuedValue.d.cts +0 -105
- package/dist/queuer/useQueuedValue.js.map +0 -1
- package/dist/queuer/useQueuer.cjs +0 -176
- package/dist/queuer/useQueuer.cjs.map +0 -1
- package/dist/queuer/useQueuer.d.cts +0 -186
- package/dist/queuer/useQueuer.js.map +0 -1
- package/dist/rate-limiter/index.cjs +0 -17
- package/dist/rate-limiter/index.d.cts +0 -6
- package/dist/rate-limiter/useRateLimitedCallback.cjs +0 -65
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +0 -61
- package/dist/rate-limiter/useRateLimitedCallback.js.map +0 -1
- package/dist/rate-limiter/useRateLimitedState.cjs +0 -115
- package/dist/rate-limiter/useRateLimitedState.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedState.d.cts +0 -107
- package/dist/rate-limiter/useRateLimitedState.js.map +0 -1
- package/dist/rate-limiter/useRateLimitedValue.cjs +0 -102
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedValue.d.cts +0 -96
- package/dist/rate-limiter/useRateLimitedValue.js.map +0 -1
- package/dist/rate-limiter/useRateLimiter.cjs +0 -167
- package/dist/rate-limiter/useRateLimiter.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimiter.d.cts +0 -179
- package/dist/rate-limiter/useRateLimiter.js.map +0 -1
- package/dist/throttler/index.cjs +0 -17
- package/dist/throttler/index.d.cts +0 -6
- package/dist/throttler/useThrottledCallback.cjs +0 -49
- package/dist/throttler/useThrottledCallback.cjs.map +0 -1
- package/dist/throttler/useThrottledCallback.d.cts +0 -45
- package/dist/throttler/useThrottledCallback.js.map +0 -1
- package/dist/throttler/useThrottledState.cjs +0 -100
- package/dist/throttler/useThrottledState.cjs.map +0 -1
- package/dist/throttler/useThrottledState.d.cts +0 -92
- package/dist/throttler/useThrottledState.js.map +0 -1
- package/dist/throttler/useThrottledValue.cjs +0 -91
- package/dist/throttler/useThrottledValue.cjs.map +0 -1
- package/dist/throttler/useThrottledValue.d.cts +0 -85
- package/dist/throttler/useThrottledValue.js.map +0 -1
- package/dist/throttler/useThrottler.cjs +0 -146
- package/dist/throttler/useThrottler.cjs.map +0 -1
- package/dist/throttler/useThrottler.d.cts +0 -157
- package/dist/throttler/useThrottler.js.map +0 -1
- package/dist/types/index.cjs +0 -9
- package/dist/types/index.d.cts +0 -1
- package/dist/utils/index.cjs +0 -9
- package/dist/utils/index.d.cts +0 -1
- package/src/async-batcher/index.ts +0 -4
- package/src/async-batcher/useAsyncBatchedCallback.ts +0 -53
- package/src/async-batcher/useAsyncBatcher.ts +0 -293
- package/src/async-debouncer/index.ts +0 -5
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +0 -54
- package/src/async-debouncer/useAsyncDebouncer.ts +0 -274
- package/src/async-queuer/index.ts +0 -4
- package/src/async-queuer/useAsyncQueuedState.ts +0 -165
- package/src/async-queuer/useAsyncQueuer.ts +0 -293
- package/src/async-rate-limiter/index.ts +0 -5
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +0 -69
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +0 -294
- package/src/async-retryer/index.ts +0 -2
- package/src/async-throttler/index.ts +0 -5
- package/src/async-throttler/useAsyncThrottledCallback.ts +0 -52
- package/src/async-throttler/useAsyncThrottler.ts +0 -285
- package/src/batcher/index.ts +0 -4
- package/src/batcher/useBatchedCallback.ts +0 -46
- package/src/batcher/useBatcher.ts +0 -241
- package/src/debouncer/index.ts +0 -7
- package/src/debouncer/useDebouncedCallback.ts +0 -51
- package/src/debouncer/useDebouncedState.ts +0 -106
- package/src/debouncer/useDebouncedValue.ts +0 -109
- package/src/debouncer/useDebouncer.ts +0 -219
- package/src/index.ts +0 -56
- package/src/provider/PacerProvider.tsx +0 -70
- package/src/provider/index.ts +0 -1
- package/src/queuer/index.ts +0 -5
- package/src/queuer/useQueuedState.ts +0 -133
- package/src/queuer/useQueuedValue.ts +0 -129
- package/src/queuer/useQueuer.ts +0 -251
- package/src/rate-limiter/index.ts +0 -6
- package/src/rate-limiter/useRateLimitedCallback.ts +0 -68
- package/src/rate-limiter/useRateLimitedState.ts +0 -124
- package/src/rate-limiter/useRateLimitedValue.ts +0 -110
- package/src/rate-limiter/useRateLimiter.ts +0 -244
- package/src/throttler/index.ts +0 -7
- package/src/throttler/useThrottledCallback.ts +0 -52
- package/src/throttler/useThrottledState.ts +0 -118
- package/src/throttler/useThrottledValue.ts +0 -104
- package/src/throttler/useThrottler.ts +0 -224
- package/src/types/index.ts +0 -1
- package/src/utils/index.ts +0 -1
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
const require_useAsyncBatcher = require('./useAsyncBatcher.cjs');
|
|
2
|
-
let preact_hooks = require("preact/hooks");
|
|
3
|
-
|
|
4
|
-
//#region src/async-batcher/useAsyncBatchedCallback.ts
|
|
5
|
-
/**
|
|
6
|
-
* A Preact hook that creates a batched version of an async callback function.
|
|
7
|
-
* This hook is a convenient wrapper around the `useAsyncBatcher` hook,
|
|
8
|
-
* providing a stable, batched async function reference for use in Preact components.
|
|
9
|
-
*
|
|
10
|
-
* The batched async function will collect individual calls into batches and execute them
|
|
11
|
-
* when batch conditions are met (max size reached, wait time elapsed, or custom logic).
|
|
12
|
-
* The returned function always returns a promise that resolves with undefined (since the
|
|
13
|
-
* batch function processes multiple items together).
|
|
14
|
-
*
|
|
15
|
-
* This hook provides a simpler API compared to `useAsyncBatcher`, making it ideal for basic
|
|
16
|
-
* async batching needs. However, it does not expose the underlying AsyncBatcher instance.
|
|
17
|
-
*
|
|
18
|
-
* For advanced usage requiring features like:
|
|
19
|
-
* - Manual batch execution
|
|
20
|
-
* - Access to batch results and state
|
|
21
|
-
* - Custom useCallback dependencies
|
|
22
|
-
*
|
|
23
|
-
* Consider using the `useAsyncBatcher` hook instead.
|
|
24
|
-
*
|
|
25
|
-
* @example
|
|
26
|
-
* ```tsx
|
|
27
|
-
* // Batch API requests
|
|
28
|
-
* const batchApiCall = useAsyncBatchedCallback(async (requests: ApiRequest[]) => {
|
|
29
|
-
* const results = await Promise.all(requests.map(req => fetch(req.url)));
|
|
30
|
-
* return results.map(res => res.json());
|
|
31
|
-
* }, {
|
|
32
|
-
* maxSize: 10, // Process when 10 requests collected
|
|
33
|
-
* wait: 1000 // Or after 1 second
|
|
34
|
-
* });
|
|
35
|
-
*
|
|
36
|
-
* // Use in event handlers
|
|
37
|
-
* <button onClick={() => batchApiCall({ url: '/api/analytics', data: eventData })}>
|
|
38
|
-
* Track Event
|
|
39
|
-
* </button>
|
|
40
|
-
* ```
|
|
41
|
-
*/
|
|
42
|
-
function useAsyncBatchedCallback(fn, options) {
|
|
43
|
-
const asyncBatchedFn = require_useAsyncBatcher.useAsyncBatcher(fn, options).addItem;
|
|
44
|
-
return (0, preact_hooks.useCallback)(async (item) => {
|
|
45
|
-
await asyncBatchedFn(item);
|
|
46
|
-
}, [asyncBatchedFn]);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
//#endregion
|
|
50
|
-
exports.useAsyncBatchedCallback = useAsyncBatchedCallback;
|
|
51
|
-
//# sourceMappingURL=useAsyncBatchedCallback.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatchedCallback.cjs","names":["useAsyncBatcher"],"sources":["../../src/async-batcher/useAsyncBatchedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncBatcher } from './useAsyncBatcher'\nimport type { PreactAsyncBatcherOptions } from './useAsyncBatcher'\n\n/**\n * A Preact hook that creates a batched version of an async callback function.\n * This hook is a convenient wrapper around the `useAsyncBatcher` hook,\n * providing a stable, batched async function reference for use in Preact components.\n *\n * The batched async function will collect individual calls into batches and execute them\n * when batch conditions are met (max size reached, wait time elapsed, or custom logic).\n * The returned function always returns a promise that resolves with undefined (since the\n * batch function processes multiple items together).\n *\n * This hook provides a simpler API compared to `useAsyncBatcher`, making it ideal for basic\n * async batching needs. However, it does not expose the underlying AsyncBatcher instance.\n *\n * For advanced usage requiring features like:\n * - Manual batch execution\n * - Access to batch results and state\n * - Custom useCallback dependencies\n *\n * Consider using the `useAsyncBatcher` hook instead.\n *\n * @example\n * ```tsx\n * // Batch API requests\n * const batchApiCall = useAsyncBatchedCallback(async (requests: ApiRequest[]) => {\n * const results = await Promise.all(requests.map(req => fetch(req.url)));\n * return results.map(res => res.json());\n * }, {\n * maxSize: 10, // Process when 10 requests collected\n * wait: 1000 // Or after 1 second\n * });\n *\n * // Use in event handlers\n * <button onClick={() => batchApiCall({ url: '/api/analytics', data: eventData })}>\n * Track Event\n * </button>\n * ```\n */\nexport function useAsyncBatchedCallback<TValue>(\n fn: (items: Array<TValue>) => Promise<unknown>,\n options: PreactAsyncBatcherOptions<TValue, {}>,\n): (item: TValue) => Promise<void> {\n const asyncBatchedFn = useAsyncBatcher(fn, options).addItem\n return useCallback(\n async (item: TValue) => {\n await asyncBatchedFn(item)\n },\n [asyncBatchedFn],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,wBACd,IACA,SACiC;CACjC,MAAM,iBAAiBA,wCAAgB,IAAI,QAAQ,CAAC;CACpD,qCACE,OAAO,SAAiB;EACtB,MAAM,eAAe,KAAK;IAE5B,CAAC,eAAe,CACjB"}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { PreactAsyncBatcherOptions } from "./useAsyncBatcher.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/async-batcher/useAsyncBatchedCallback.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* A Preact hook that creates a batched version of an async callback function.
|
|
6
|
-
* This hook is a convenient wrapper around the `useAsyncBatcher` hook,
|
|
7
|
-
* providing a stable, batched async function reference for use in Preact components.
|
|
8
|
-
*
|
|
9
|
-
* The batched async function will collect individual calls into batches and execute them
|
|
10
|
-
* when batch conditions are met (max size reached, wait time elapsed, or custom logic).
|
|
11
|
-
* The returned function always returns a promise that resolves with undefined (since the
|
|
12
|
-
* batch function processes multiple items together).
|
|
13
|
-
*
|
|
14
|
-
* This hook provides a simpler API compared to `useAsyncBatcher`, making it ideal for basic
|
|
15
|
-
* async batching needs. However, it does not expose the underlying AsyncBatcher instance.
|
|
16
|
-
*
|
|
17
|
-
* For advanced usage requiring features like:
|
|
18
|
-
* - Manual batch execution
|
|
19
|
-
* - Access to batch results and state
|
|
20
|
-
* - Custom useCallback dependencies
|
|
21
|
-
*
|
|
22
|
-
* Consider using the `useAsyncBatcher` hook instead.
|
|
23
|
-
*
|
|
24
|
-
* @example
|
|
25
|
-
* ```tsx
|
|
26
|
-
* // Batch API requests
|
|
27
|
-
* const batchApiCall = useAsyncBatchedCallback(async (requests: ApiRequest[]) => {
|
|
28
|
-
* const results = await Promise.all(requests.map(req => fetch(req.url)));
|
|
29
|
-
* return results.map(res => res.json());
|
|
30
|
-
* }, {
|
|
31
|
-
* maxSize: 10, // Process when 10 requests collected
|
|
32
|
-
* wait: 1000 // Or after 1 second
|
|
33
|
-
* });
|
|
34
|
-
*
|
|
35
|
-
* // Use in event handlers
|
|
36
|
-
* <button onClick={() => batchApiCall({ url: '/api/analytics', data: eventData })}>
|
|
37
|
-
* Track Event
|
|
38
|
-
* </button>
|
|
39
|
-
* ```
|
|
40
|
-
*/
|
|
41
|
-
declare function useAsyncBatchedCallback<TValue>(fn: (items: Array<TValue>) => Promise<unknown>, options: PreactAsyncBatcherOptions<TValue, {}>): (item: TValue) => Promise<void>;
|
|
42
|
-
//#endregion
|
|
43
|
-
export { useAsyncBatchedCallback };
|
|
44
|
-
//# sourceMappingURL=useAsyncBatchedCallback.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatchedCallback.js","names":[],"sources":["../../src/async-batcher/useAsyncBatchedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncBatcher } from './useAsyncBatcher'\nimport type { PreactAsyncBatcherOptions } from './useAsyncBatcher'\n\n/**\n * A Preact hook that creates a batched version of an async callback function.\n * This hook is a convenient wrapper around the `useAsyncBatcher` hook,\n * providing a stable, batched async function reference for use in Preact components.\n *\n * The batched async function will collect individual calls into batches and execute them\n * when batch conditions are met (max size reached, wait time elapsed, or custom logic).\n * The returned function always returns a promise that resolves with undefined (since the\n * batch function processes multiple items together).\n *\n * This hook provides a simpler API compared to `useAsyncBatcher`, making it ideal for basic\n * async batching needs. However, it does not expose the underlying AsyncBatcher instance.\n *\n * For advanced usage requiring features like:\n * - Manual batch execution\n * - Access to batch results and state\n * - Custom useCallback dependencies\n *\n * Consider using the `useAsyncBatcher` hook instead.\n *\n * @example\n * ```tsx\n * // Batch API requests\n * const batchApiCall = useAsyncBatchedCallback(async (requests: ApiRequest[]) => {\n * const results = await Promise.all(requests.map(req => fetch(req.url)));\n * return results.map(res => res.json());\n * }, {\n * maxSize: 10, // Process when 10 requests collected\n * wait: 1000 // Or after 1 second\n * });\n *\n * // Use in event handlers\n * <button onClick={() => batchApiCall({ url: '/api/analytics', data: eventData })}>\n * Track Event\n * </button>\n * ```\n */\nexport function useAsyncBatchedCallback<TValue>(\n fn: (items: Array<TValue>) => Promise<unknown>,\n options: PreactAsyncBatcherOptions<TValue, {}>,\n): (item: TValue) => Promise<void> {\n const asyncBatchedFn = useAsyncBatcher(fn, options).addItem\n return useCallback(\n async (item: TValue) => {\n await asyncBatchedFn(item)\n },\n [asyncBatchedFn],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,wBACd,IACA,SACiC;CACjC,MAAM,iBAAiB,gBAAgB,IAAI,QAAQ,CAAC;CACpD,OAAO,YACL,OAAO,SAAiB;EACtB,MAAM,eAAe,KAAK;IAE5B,CAAC,eAAe,CACjB"}
|
|
@@ -1,217 +0,0 @@
|
|
|
1
|
-
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
|
-
let preact_hooks = require("preact/hooks");
|
|
3
|
-
let _tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
|
|
4
|
-
let _tanstack_preact_store = require("@tanstack/preact-store");
|
|
5
|
-
|
|
6
|
-
//#region src/async-batcher/useAsyncBatcher.ts
|
|
7
|
-
/**
|
|
8
|
-
* A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.
|
|
9
|
-
*
|
|
10
|
-
* This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:
|
|
11
|
-
* - Handles promises and returns results from batch executions
|
|
12
|
-
* - Provides error handling with configurable error behavior
|
|
13
|
-
* - Tracks success, error, and settle counts separately
|
|
14
|
-
* - Has state tracking for when batches are executing
|
|
15
|
-
* - Returns the result of the batch function execution
|
|
16
|
-
*
|
|
17
|
-
* Features:
|
|
18
|
-
* - Configurable batch size and wait time
|
|
19
|
-
* - Custom batch processing logic via getShouldExecute
|
|
20
|
-
* - Event callbacks for monitoring batch operations
|
|
21
|
-
* - Error handling for failed batch operations
|
|
22
|
-
* - Automatic or manual batch processing
|
|
23
|
-
*
|
|
24
|
-
* The batcher collects items and processes them in batches based on:
|
|
25
|
-
* - Maximum batch size (number of items per batch)
|
|
26
|
-
* - Time-based batching (process after X milliseconds)
|
|
27
|
-
* - Custom batch processing logic via getShouldExecute
|
|
28
|
-
*
|
|
29
|
-
* Error Handling:
|
|
30
|
-
* - If an `onError` handler is provided, it will be called with the error and batcher instance
|
|
31
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
32
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
33
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
34
|
-
* - The error state can be checked using the underlying AsyncBatcher instance
|
|
35
|
-
*
|
|
36
|
-
* ## State Management and Selector
|
|
37
|
-
*
|
|
38
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
39
|
-
* in two ways:
|
|
40
|
-
*
|
|
41
|
-
* **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
42
|
-
*
|
|
43
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
44
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
45
|
-
* in child components.
|
|
46
|
-
*
|
|
47
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
48
|
-
*
|
|
49
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
50
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
51
|
-
* state changes occur.
|
|
52
|
-
*
|
|
53
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
54
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
55
|
-
* re-renders and gives you full control over when your component updates.
|
|
56
|
-
*
|
|
57
|
-
* Available state properties:
|
|
58
|
-
* - `errorCount`: Number of batch executions that have resulted in errors
|
|
59
|
-
* - `failedItems`: Array of items that failed during batch processing
|
|
60
|
-
* - `isEmpty`: Whether the batcher has no items to process
|
|
61
|
-
* - `isExecuting`: Whether a batch is currently being processed asynchronously
|
|
62
|
-
* - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing
|
|
63
|
-
* - `isRunning`: Whether the batcher is active and will process items automatically
|
|
64
|
-
* - `items`: Array of items currently queued for batch processing
|
|
65
|
-
* - `lastResult`: The result from the most recent batch execution
|
|
66
|
-
* - `settleCount`: Number of batch executions that have completed (success or error)
|
|
67
|
-
* - `size`: Number of items currently in the batch queue
|
|
68
|
-
* - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')
|
|
69
|
-
* - `successCount`: Number of batch executions that have completed successfully
|
|
70
|
-
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
71
|
-
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
72
|
-
*
|
|
73
|
-
* ## Unmount behavior
|
|
74
|
-
*
|
|
75
|
-
* By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.
|
|
76
|
-
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
77
|
-
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
78
|
-
*
|
|
79
|
-
* ```tsx
|
|
80
|
-
* const batcher = useAsyncBatcher(fn, {
|
|
81
|
-
* maxSize: 10,
|
|
82
|
-
* wait: 2000,
|
|
83
|
-
* onUnmount: (b) => b.flush()
|
|
84
|
-
* });
|
|
85
|
-
* ```
|
|
86
|
-
*
|
|
87
|
-
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
88
|
-
* If your batch function updates Preact state, those updates may run after the component has
|
|
89
|
-
* unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
|
|
90
|
-
* accordingly when using onUnmount with flush.
|
|
91
|
-
*
|
|
92
|
-
* @example
|
|
93
|
-
* ```tsx
|
|
94
|
-
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
95
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
96
|
-
* async (items) => {
|
|
97
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
98
|
-
* return results;
|
|
99
|
-
* },
|
|
100
|
-
* { maxSize: 10, wait: 2000 }
|
|
101
|
-
* );
|
|
102
|
-
*
|
|
103
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
104
|
-
* <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
|
|
105
|
-
* {({ size }) => (
|
|
106
|
-
* <div>Batch Size: {size}</div>
|
|
107
|
-
* )}
|
|
108
|
-
* </asyncBatcher.Subscribe>
|
|
109
|
-
*
|
|
110
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
111
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
112
|
-
* async (items) => {
|
|
113
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
114
|
-
* return results;
|
|
115
|
-
* },
|
|
116
|
-
* { maxSize: 10, wait: 2000 },
|
|
117
|
-
* (state) => ({
|
|
118
|
-
* isExecuting: state.isExecuting,
|
|
119
|
-
* isPending: state.isPending,
|
|
120
|
-
* status: state.status
|
|
121
|
-
* })
|
|
122
|
-
* );
|
|
123
|
-
*
|
|
124
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
125
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
126
|
-
* async (items) => {
|
|
127
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
128
|
-
* return results;
|
|
129
|
-
* },
|
|
130
|
-
* { maxSize: 10, wait: 2000 },
|
|
131
|
-
* (state) => ({
|
|
132
|
-
* lastResult: state.lastResult,
|
|
133
|
-
* successCount: state.successCount,
|
|
134
|
-
* totalItemsProcessed: state.totalItemsProcessed
|
|
135
|
-
* })
|
|
136
|
-
* );
|
|
137
|
-
*
|
|
138
|
-
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
139
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
140
|
-
* async (items) => {
|
|
141
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
142
|
-
* return results;
|
|
143
|
-
* },
|
|
144
|
-
* {
|
|
145
|
-
* maxSize: 10,
|
|
146
|
-
* wait: 2000,
|
|
147
|
-
* onError: (error) => console.error('Batch processing failed:', error)
|
|
148
|
-
* },
|
|
149
|
-
* (state) => ({
|
|
150
|
-
* errorCount: state.errorCount,
|
|
151
|
-
* failedItems: state.failedItems,
|
|
152
|
-
* totalItemsFailed: state.totalItemsFailed
|
|
153
|
-
* })
|
|
154
|
-
* );
|
|
155
|
-
*
|
|
156
|
-
* // Complete example with all callbacks
|
|
157
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
158
|
-
* async (items) => {
|
|
159
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
160
|
-
* return results;
|
|
161
|
-
* },
|
|
162
|
-
* {
|
|
163
|
-
* maxSize: 10,
|
|
164
|
-
* wait: 2000,
|
|
165
|
-
* onSuccess: (result) => {
|
|
166
|
-
* console.log('Batch processed successfully:', result);
|
|
167
|
-
* },
|
|
168
|
-
* onError: (error) => {
|
|
169
|
-
* console.error('Batch processing failed:', error);
|
|
170
|
-
* }
|
|
171
|
-
* }
|
|
172
|
-
* );
|
|
173
|
-
*
|
|
174
|
-
* // Add items to batch
|
|
175
|
-
* asyncBatcher.addItem(newItem);
|
|
176
|
-
*
|
|
177
|
-
* // Manually execute batch
|
|
178
|
-
* const result = await asyncBatcher.execute();
|
|
179
|
-
*
|
|
180
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
181
|
-
* const { isExecuting, lastResult, size } = asyncBatcher.state;
|
|
182
|
-
* ```
|
|
183
|
-
*/
|
|
184
|
-
function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
185
|
-
const mergedOptions = {
|
|
186
|
-
...require_PacerProvider.useDefaultPacerOptions().asyncBatcher,
|
|
187
|
-
...options
|
|
188
|
-
};
|
|
189
|
-
const [asyncBatcher] = (0, preact_hooks.useState)(() => {
|
|
190
|
-
const batcherInstance = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
|
|
191
|
-
batcherInstance.Subscribe = function Subscribe(props) {
|
|
192
|
-
const selected = (0, _tanstack_preact_store.useSelector)(batcherInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
|
|
193
|
-
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
194
|
-
};
|
|
195
|
-
return batcherInstance;
|
|
196
|
-
});
|
|
197
|
-
asyncBatcher.fn = fn;
|
|
198
|
-
asyncBatcher.setOptions(mergedOptions);
|
|
199
|
-
(0, preact_hooks.useEffect)(() => {
|
|
200
|
-
return () => {
|
|
201
|
-
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
202
|
-
else {
|
|
203
|
-
asyncBatcher.cancel();
|
|
204
|
-
asyncBatcher.abort();
|
|
205
|
-
}
|
|
206
|
-
};
|
|
207
|
-
}, []);
|
|
208
|
-
const state = (0, _tanstack_preact_store.useSelector)(asyncBatcher.store, selector, { compare: _tanstack_preact_store.shallow });
|
|
209
|
-
return (0, preact_hooks.useMemo)(() => ({
|
|
210
|
-
...asyncBatcher,
|
|
211
|
-
state
|
|
212
|
-
}), [asyncBatcher, state]);
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
//#endregion
|
|
216
|
-
exports.useAsyncBatcher = useAsyncBatcher;
|
|
217
|
-
//# sourceMappingURL=useAsyncBatcher.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher","shallow"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(batcherInstance.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(asyncBatcher.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,iDAA+B;EACpC,MAAM,kBAAkB,IAAIC,2CAC1B,IACA,cACD;EAED,gBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,mDAAuB,gBAAgB,OAAO,MAAM,UAAU,EAClE,SAASC,gCACV,CAAC;GAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;EAGZ,OAAO;GACP;CAEF,aAAa,KAAK;CAClB,aAAa,WAAW,cAAc;CAGtC,kCAAgB;EACd,aAAa;GACX,IAAI,cAAc,WAChB,cAAc,UAAU,aAAa;QAChC;IACL,aAAa,QAAQ;IACrB,aAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,gDAAoB,aAAa,OAAO,UAAU,EAAE,SAASA,gCAAS,CAAC;CAE7E,wCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/pacer/async-batcher";
|
|
2
|
-
import { Store } from "@tanstack/preact-store";
|
|
3
|
-
import { ComponentChildren } from "preact";
|
|
4
|
-
|
|
5
|
-
//#region src/async-batcher/useAsyncBatcher.d.ts
|
|
6
|
-
interface PreactAsyncBatcherOptions<TValue, TSelected = {}> extends AsyncBatcherOptions<TValue> {
|
|
7
|
-
/**
|
|
8
|
-
* Optional callback invoked when the component unmounts. Receives the batcher instance.
|
|
9
|
-
* When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
|
|
10
|
-
*/
|
|
11
|
-
onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void;
|
|
12
|
-
}
|
|
13
|
-
interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
|
|
14
|
-
/**
|
|
15
|
-
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
|
|
16
|
-
*
|
|
17
|
-
* This is useful for opting into state re-renders for specific parts of the batcher state
|
|
18
|
-
* deep in your component tree without needing to pass a selector to the hook.
|
|
19
|
-
*
|
|
20
|
-
* @example
|
|
21
|
-
* <batcher.Subscribe selector={(state) => ({ size: state.size })}>
|
|
22
|
-
* {({ size }) => (
|
|
23
|
-
* <div>Batch Size: {size}</div>
|
|
24
|
-
* )}
|
|
25
|
-
* </batcher.Subscribe>
|
|
26
|
-
*/
|
|
27
|
-
Subscribe: <TSelected>(props: {
|
|
28
|
-
selector: (state: AsyncBatcherState<TValue>) => TSelected;
|
|
29
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
|
|
30
|
-
}) => ComponentChildren;
|
|
31
|
-
/**
|
|
32
|
-
* Reactive state that will be updated and re-rendered when the batcher state changes
|
|
33
|
-
*
|
|
34
|
-
* Use this instead of `batcher.store.state`
|
|
35
|
-
*/
|
|
36
|
-
readonly state: Readonly<TSelected>;
|
|
37
|
-
/**
|
|
38
|
-
* @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.
|
|
39
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
40
|
-
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
41
|
-
*/
|
|
42
|
-
readonly store: Store<Readonly<AsyncBatcherState<TValue>>>;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
|
-
* A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.
|
|
46
|
-
*
|
|
47
|
-
* This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:
|
|
48
|
-
* - Handles promises and returns results from batch executions
|
|
49
|
-
* - Provides error handling with configurable error behavior
|
|
50
|
-
* - Tracks success, error, and settle counts separately
|
|
51
|
-
* - Has state tracking for when batches are executing
|
|
52
|
-
* - Returns the result of the batch function execution
|
|
53
|
-
*
|
|
54
|
-
* Features:
|
|
55
|
-
* - Configurable batch size and wait time
|
|
56
|
-
* - Custom batch processing logic via getShouldExecute
|
|
57
|
-
* - Event callbacks for monitoring batch operations
|
|
58
|
-
* - Error handling for failed batch operations
|
|
59
|
-
* - Automatic or manual batch processing
|
|
60
|
-
*
|
|
61
|
-
* The batcher collects items and processes them in batches based on:
|
|
62
|
-
* - Maximum batch size (number of items per batch)
|
|
63
|
-
* - Time-based batching (process after X milliseconds)
|
|
64
|
-
* - Custom batch processing logic via getShouldExecute
|
|
65
|
-
*
|
|
66
|
-
* Error Handling:
|
|
67
|
-
* - If an `onError` handler is provided, it will be called with the error and batcher instance
|
|
68
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
69
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
70
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
71
|
-
* - The error state can be checked using the underlying AsyncBatcher instance
|
|
72
|
-
*
|
|
73
|
-
* ## State Management and Selector
|
|
74
|
-
*
|
|
75
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
76
|
-
* in two ways:
|
|
77
|
-
*
|
|
78
|
-
* **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
79
|
-
*
|
|
80
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
81
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
82
|
-
* in child components.
|
|
83
|
-
*
|
|
84
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
85
|
-
*
|
|
86
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
87
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
88
|
-
* state changes occur.
|
|
89
|
-
*
|
|
90
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
91
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
92
|
-
* re-renders and gives you full control over when your component updates.
|
|
93
|
-
*
|
|
94
|
-
* Available state properties:
|
|
95
|
-
* - `errorCount`: Number of batch executions that have resulted in errors
|
|
96
|
-
* - `failedItems`: Array of items that failed during batch processing
|
|
97
|
-
* - `isEmpty`: Whether the batcher has no items to process
|
|
98
|
-
* - `isExecuting`: Whether a batch is currently being processed asynchronously
|
|
99
|
-
* - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing
|
|
100
|
-
* - `isRunning`: Whether the batcher is active and will process items automatically
|
|
101
|
-
* - `items`: Array of items currently queued for batch processing
|
|
102
|
-
* - `lastResult`: The result from the most recent batch execution
|
|
103
|
-
* - `settleCount`: Number of batch executions that have completed (success or error)
|
|
104
|
-
* - `size`: Number of items currently in the batch queue
|
|
105
|
-
* - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')
|
|
106
|
-
* - `successCount`: Number of batch executions that have completed successfully
|
|
107
|
-
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
108
|
-
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
109
|
-
*
|
|
110
|
-
* ## Unmount behavior
|
|
111
|
-
*
|
|
112
|
-
* By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.
|
|
113
|
-
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
114
|
-
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
115
|
-
*
|
|
116
|
-
* ```tsx
|
|
117
|
-
* const batcher = useAsyncBatcher(fn, {
|
|
118
|
-
* maxSize: 10,
|
|
119
|
-
* wait: 2000,
|
|
120
|
-
* onUnmount: (b) => b.flush()
|
|
121
|
-
* });
|
|
122
|
-
* ```
|
|
123
|
-
*
|
|
124
|
-
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
125
|
-
* If your batch function updates Preact state, those updates may run after the component has
|
|
126
|
-
* unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
|
|
127
|
-
* accordingly when using onUnmount with flush.
|
|
128
|
-
*
|
|
129
|
-
* @example
|
|
130
|
-
* ```tsx
|
|
131
|
-
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
132
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
133
|
-
* async (items) => {
|
|
134
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
135
|
-
* return results;
|
|
136
|
-
* },
|
|
137
|
-
* { maxSize: 10, wait: 2000 }
|
|
138
|
-
* );
|
|
139
|
-
*
|
|
140
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
141
|
-
* <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>
|
|
142
|
-
* {({ size }) => (
|
|
143
|
-
* <div>Batch Size: {size}</div>
|
|
144
|
-
* )}
|
|
145
|
-
* </asyncBatcher.Subscribe>
|
|
146
|
-
*
|
|
147
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
148
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
149
|
-
* async (items) => {
|
|
150
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
151
|
-
* return results;
|
|
152
|
-
* },
|
|
153
|
-
* { maxSize: 10, wait: 2000 },
|
|
154
|
-
* (state) => ({
|
|
155
|
-
* isExecuting: state.isExecuting,
|
|
156
|
-
* isPending: state.isPending,
|
|
157
|
-
* status: state.status
|
|
158
|
-
* })
|
|
159
|
-
* );
|
|
160
|
-
*
|
|
161
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
162
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
163
|
-
* async (items) => {
|
|
164
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
165
|
-
* return results;
|
|
166
|
-
* },
|
|
167
|
-
* { maxSize: 10, wait: 2000 },
|
|
168
|
-
* (state) => ({
|
|
169
|
-
* lastResult: state.lastResult,
|
|
170
|
-
* successCount: state.successCount,
|
|
171
|
-
* totalItemsProcessed: state.totalItemsProcessed
|
|
172
|
-
* })
|
|
173
|
-
* );
|
|
174
|
-
*
|
|
175
|
-
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
176
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
177
|
-
* async (items) => {
|
|
178
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
179
|
-
* return results;
|
|
180
|
-
* },
|
|
181
|
-
* {
|
|
182
|
-
* maxSize: 10,
|
|
183
|
-
* wait: 2000,
|
|
184
|
-
* onError: (error) => console.error('Batch processing failed:', error)
|
|
185
|
-
* },
|
|
186
|
-
* (state) => ({
|
|
187
|
-
* errorCount: state.errorCount,
|
|
188
|
-
* failedItems: state.failedItems,
|
|
189
|
-
* totalItemsFailed: state.totalItemsFailed
|
|
190
|
-
* })
|
|
191
|
-
* );
|
|
192
|
-
*
|
|
193
|
-
* // Complete example with all callbacks
|
|
194
|
-
* const asyncBatcher = useAsyncBatcher(
|
|
195
|
-
* async (items) => {
|
|
196
|
-
* const results = await Promise.all(items.map(item => processItem(item)));
|
|
197
|
-
* return results;
|
|
198
|
-
* },
|
|
199
|
-
* {
|
|
200
|
-
* maxSize: 10,
|
|
201
|
-
* wait: 2000,
|
|
202
|
-
* onSuccess: (result) => {
|
|
203
|
-
* console.log('Batch processed successfully:', result);
|
|
204
|
-
* },
|
|
205
|
-
* onError: (error) => {
|
|
206
|
-
* console.error('Batch processing failed:', error);
|
|
207
|
-
* }
|
|
208
|
-
* }
|
|
209
|
-
* );
|
|
210
|
-
*
|
|
211
|
-
* // Add items to batch
|
|
212
|
-
* asyncBatcher.addItem(newItem);
|
|
213
|
-
*
|
|
214
|
-
* // Manually execute batch
|
|
215
|
-
* const result = await asyncBatcher.execute();
|
|
216
|
-
*
|
|
217
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
218
|
-
* const { isExecuting, lastResult, size } = asyncBatcher.state;
|
|
219
|
-
* ```
|
|
220
|
-
*/
|
|
221
|
-
declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: PreactAsyncBatcherOptions<TValue, TSelected>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): PreactAsyncBatcher<TValue, TSelected>;
|
|
222
|
-
//#endregion
|
|
223
|
-
export { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatcher };
|
|
224
|
-
//# sourceMappingURL=useAsyncBatcher.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the component unmounts. Receives the batcher instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (batcher: PreactAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.\n *\n * This is useful for opting into state re-renders for specific parts of the batcher state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <batcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `batcher.state` instead of `batcher.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.\n * Although, you can make the state reactive by using the `useSelector` in your own usage.\n */\n readonly store: Store<Readonly<AsyncBatcherState<TValue>>>\n}\n\n/**\n * A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.\n *\n * This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:\n * - Handles promises and returns results from batch executions\n * - Provides error handling with configurable error behavior\n * - Tracks success, error, and settle counts separately\n * - Has state tracking for when batches are executing\n * - Returns the result of the batch function execution\n *\n * Features:\n * - Configurable batch size and wait time\n * - Custom batch processing logic via getShouldExecute\n * - Event callbacks for monitoring batch operations\n * - Error handling for failed batch operations\n * - Automatic or manual batch processing\n *\n * The batcher collects items and processes them in batches based on:\n * - Maximum batch size (number of items per batch)\n * - Time-based batching (process after X milliseconds)\n * - Custom batch processing logic via getShouldExecute\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and batcher instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncBatcher instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without\n * needing to pass a selector to the hook. This is ideal when you want to subscribe to state\n * in child components.\n *\n * **2. Using the `selector` parameter (For hook-level subscriptions)**\n *\n * The `selector` parameter allows you to specify which state changes will trigger a re-render\n * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant\n * state changes occur.\n *\n * **By default, there will be no reactive state subscriptions** and you must opt-in to state\n * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary\n * re-renders and gives you full control over when your component updates.\n *\n * Available state properties:\n * - `errorCount`: Number of batch executions that have resulted in errors\n * - `failedItems`: Array of items that failed during batch processing\n * - `isEmpty`: Whether the batcher has no items to process\n * - `isExecuting`: Whether a batch is currently being processed asynchronously\n * - `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing\n * - `isRunning`: Whether the batcher is active and will process items automatically\n * - `items`: Array of items currently queued for batch processing\n * - `lastResult`: The result from the most recent batch execution\n * - `settleCount`: Number of batch executions that have completed (success or error)\n * - `size`: Number of items currently in the batch queue\n * - `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')\n * - `successCount`: Number of batch executions that have completed successfully\n * - `totalItemsProcessed`: Total number of items processed across all batches\n * - `totalItemsFailed`: Total number of items that have failed processing\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const batcher = useAsyncBatcher(fn, {\n * maxSize: 10,\n * wait: 2000,\n * onUnmount: (b) => b.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your batch function updates Preact state, those updates may run after the component has\n * unmounted, which can cause \"setState on unmounted component\" warnings. Guard your callbacks\n * accordingly when using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Basic async batcher for API requests - no reactive state subscriptions\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncBatcher.Subscribe selector={(state) => ({ size: state.size })}>\n * {({ size }) => (\n * <div>Batch Size: {size}</div>\n * )}\n * </asyncBatcher.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * { maxSize: 10, wait: 2000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * totalItemsProcessed: state.totalItemsProcessed\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onError: (error) => console.error('Batch processing failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * failedItems: state.failedItems,\n * totalItemsFailed: state.totalItemsFailed\n * })\n * );\n *\n * // Complete example with all callbacks\n * const asyncBatcher = useAsyncBatcher(\n * async (items) => {\n * const results = await Promise.all(items.map(item => processItem(item)));\n * return results;\n * },\n * {\n * maxSize: 10,\n * wait: 2000,\n * onSuccess: (result) => {\n * console.log('Batch processed successfully:', result);\n * },\n * onError: (error) => {\n * console.error('Batch processing failed:', error);\n * }\n * }\n * );\n *\n * // Add items to batch\n * asyncBatcher.addItem(newItem);\n *\n * // Manually execute batch\n * const result = await asyncBatcher.execute();\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, size } = asyncBatcher.state;\n * ```\n */\nexport function useAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: PreactAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as PreactAsyncBatcherOptions<TValue, TSelected>\n const [asyncBatcher] = useState(() => {\n const batcherInstance = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncBatcher<TValue, TSelected>\n\n batcherInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(batcherInstance.store, props.selector, {\n compare: shallow,\n })\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return batcherInstance\n })\n\n asyncBatcher.fn = fn\n asyncBatcher.setOptions(mergedOptions)\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n const state = useSelector(asyncBatcher.store, selector, { compare: shallow })\n\n return useMemo(\n () =>\n ({\n ...asyncBatcher,\n state,\n }) as PreactAsyncBatcher<TValue, TSelected>, // omit `store` in favor of `state`\n [asyncBatcher, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0OA,SAAgB,gBACd,IACA,UAAwD,EAAE,EAC1D,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,gBAAgB,eAAe;EACpC,MAAM,kBAAkB,IAAI,aAC1B,IACA,cACD;EAED,gBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,YAAY,gBAAgB,OAAO,MAAM,UAAU,EAClE,SAAS,SACV,CAAC;GAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;EAGZ,OAAO;GACP;CAEF,aAAa,KAAK;CAClB,aAAa,WAAW,cAAc;CAGtC,gBAAgB;EACd,aAAa;GACX,IAAI,cAAc,WAChB,cAAc,UAAU,aAAa;QAChC;IACL,aAAa,QAAQ;IACrB,aAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,QAAQ,YAAY,aAAa,OAAO,UAAU,EAAE,SAAS,SAAS,CAAC;CAE7E,OAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_useAsyncDebouncer = require('./useAsyncDebouncer.cjs');
|
|
3
|
-
const require_useAsyncDebouncedCallback = require('./useAsyncDebouncedCallback.cjs');
|
|
4
|
-
|
|
5
|
-
exports.useAsyncDebouncedCallback = require_useAsyncDebouncedCallback.useAsyncDebouncedCallback;
|
|
6
|
-
exports.useAsyncDebouncer = require_useAsyncDebouncer.useAsyncDebouncer;
|
|
7
|
-
var _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
|
|
8
|
-
Object.keys(_tanstack_pacer_async_debouncer).forEach(function (k) {
|
|
9
|
-
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
|
10
|
-
enumerable: true,
|
|
11
|
-
get: function () { return _tanstack_pacer_async_debouncer[k]; }
|
|
12
|
-
});
|
|
13
|
-
});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncer } from "./useAsyncDebouncer.cjs";
|
|
2
|
-
import { useAsyncDebouncedCallback } from "./useAsyncDebouncedCallback.cjs";
|
|
3
|
-
export * from "@tanstack/pacer/async-debouncer";
|
|
4
|
-
export { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncedCallback, useAsyncDebouncer };
|