@tanstack/preact-pacer 0.19.4 → 0.21.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 +6 -6
- package/dist/async-batcher/index.cjs +1 -0
- package/dist/async-batcher/index.d.cts +2 -2
- package/dist/async-batcher/index.d.ts +2 -2
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +2 -2
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +1 -1
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +2 -3
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +2 -3
- package/dist/async-batcher/useAsyncBatchedCallback.js +2 -2
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +1 -1
- package/dist/async-batcher/useAsyncBatcher.cjs +30 -2
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/useAsyncBatcher.d.cts +28 -2
- package/dist/async-batcher/useAsyncBatcher.d.ts +28 -2
- package/dist/async-batcher/useAsyncBatcher.js +32 -4
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
- package/dist/async-debouncer/index.cjs +1 -0
- package/dist/async-debouncer/index.d.cts +2 -2
- package/dist/async-debouncer/index.d.ts +2 -2
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +2 -2
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +2 -2
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.cjs +26 -4
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +28 -3
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +27 -2
- package/dist/async-debouncer/useAsyncDebouncer.js +27 -5
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
- package/dist/async-queuer/index.cjs +1 -0
- package/dist/async-queuer/index.d.cts +2 -2
- package/dist/async-queuer/index.d.ts +2 -2
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuedState.d.cts +3 -3
- package/dist/async-queuer/useAsyncQueuedState.d.ts +3 -3
- package/dist/async-queuer/useAsyncQueuedState.js.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +30 -2
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/useAsyncQueuer.d.cts +28 -2
- package/dist/async-queuer/useAsyncQueuer.d.ts +28 -2
- package/dist/async-queuer/useAsyncQueuer.js +32 -4
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
- package/dist/async-rate-limiter/index.cjs +1 -0
- package/dist/async-rate-limiter/index.d.cts +2 -2
- package/dist/async-rate-limiter/index.d.ts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +2 -2
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +14 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +15 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +15 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +16 -4
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
- package/dist/async-throttler/index.cjs +1 -0
- package/dist/async-throttler/index.d.cts +2 -2
- package/dist/async-throttler/index.d.ts +2 -2
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +1 -1
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +2 -2
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +2 -2
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.cjs +28 -4
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/useAsyncThrottler.d.cts +27 -2
- package/dist/async-throttler/useAsyncThrottler.d.ts +27 -2
- package/dist/async-throttler/useAsyncThrottler.js +29 -5
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
- package/dist/batcher/index.cjs +1 -0
- package/dist/batcher/index.d.cts +2 -2
- package/dist/batcher/index.d.ts +2 -2
- package/dist/batcher/useBatchedCallback.cjs +1 -1
- package/dist/batcher/useBatchedCallback.cjs.map +1 -1
- package/dist/batcher/useBatchedCallback.d.cts +2 -3
- package/dist/batcher/useBatchedCallback.d.ts +2 -3
- package/dist/batcher/useBatchedCallback.js +1 -1
- package/dist/batcher/useBatchedCallback.js.map +1 -1
- package/dist/batcher/useBatcher.cjs +21 -2
- package/dist/batcher/useBatcher.cjs.map +1 -1
- package/dist/batcher/useBatcher.d.cts +22 -2
- package/dist/batcher/useBatcher.d.ts +22 -2
- package/dist/batcher/useBatcher.js +23 -4
- package/dist/batcher/useBatcher.js.map +1 -1
- package/dist/debouncer/index.cjs +1 -0
- package/dist/debouncer/index.d.cts +2 -2
- package/dist/debouncer/index.d.ts +2 -2
- package/dist/debouncer/useDebouncedCallback.cjs.map +1 -1
- package/dist/debouncer/useDebouncedCallback.d.cts +2 -2
- package/dist/debouncer/useDebouncedCallback.d.ts +2 -2
- package/dist/debouncer/useDebouncedCallback.js.map +1 -1
- package/dist/debouncer/useDebouncedState.cjs.map +1 -1
- package/dist/debouncer/useDebouncedState.d.cts +3 -3
- package/dist/debouncer/useDebouncedState.d.ts +3 -3
- package/dist/debouncer/useDebouncedState.js.map +1 -1
- package/dist/debouncer/useDebouncedValue.cjs.map +1 -1
- package/dist/debouncer/useDebouncedValue.d.cts +3 -3
- package/dist/debouncer/useDebouncedValue.d.ts +3 -3
- package/dist/debouncer/useDebouncedValue.js.map +1 -1
- package/dist/debouncer/useDebouncer.cjs +17 -4
- package/dist/debouncer/useDebouncer.cjs.map +1 -1
- package/dist/debouncer/useDebouncer.d.cts +21 -2
- package/dist/debouncer/useDebouncer.d.ts +21 -2
- package/dist/debouncer/useDebouncer.js +18 -5
- package/dist/debouncer/useDebouncer.js.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/provider/PacerProvider.cjs.map +1 -1
- package/dist/provider/PacerProvider.d.cts +2 -2
- package/dist/provider/PacerProvider.d.ts +2 -2
- package/dist/provider/PacerProvider.js.map +1 -1
- package/dist/provider/index.cjs +1 -0
- package/dist/queuer/index.cjs +1 -0
- package/dist/queuer/index.d.cts +2 -2
- package/dist/queuer/index.d.ts +2 -2
- package/dist/queuer/useQueuedState.cjs.map +1 -1
- package/dist/queuer/useQueuedState.d.cts +3 -3
- package/dist/queuer/useQueuedState.d.ts +3 -3
- package/dist/queuer/useQueuedState.js.map +1 -1
- package/dist/queuer/useQueuedValue.cjs.map +1 -1
- package/dist/queuer/useQueuedValue.d.cts +3 -3
- package/dist/queuer/useQueuedValue.d.ts +3 -3
- package/dist/queuer/useQueuedValue.js.map +1 -1
- package/dist/queuer/useQueuer.cjs +21 -2
- package/dist/queuer/useQueuer.cjs.map +1 -1
- package/dist/queuer/useQueuer.d.cts +22 -2
- package/dist/queuer/useQueuer.d.ts +22 -2
- package/dist/queuer/useQueuer.js +23 -4
- package/dist/queuer/useQueuer.js.map +1 -1
- package/dist/rate-limiter/index.cjs +1 -0
- package/dist/rate-limiter/index.d.cts +2 -2
- package/dist/rate-limiter/index.d.ts +2 -2
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +2 -2
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +2 -2
- package/dist/rate-limiter/useRateLimitedCallback.js.map +1 -1
- package/dist/rate-limiter/useRateLimitedState.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimitedState.d.cts +3 -3
- package/dist/rate-limiter/useRateLimitedState.d.ts +3 -3
- package/dist/rate-limiter/useRateLimitedState.js.map +1 -1
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimitedValue.d.cts +3 -3
- package/dist/rate-limiter/useRateLimitedValue.d.ts +3 -3
- package/dist/rate-limiter/useRateLimitedValue.js.map +1 -1
- package/dist/rate-limiter/useRateLimiter.cjs +7 -2
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/useRateLimiter.d.cts +9 -2
- package/dist/rate-limiter/useRateLimiter.d.ts +9 -2
- package/dist/rate-limiter/useRateLimiter.js +9 -4
- package/dist/rate-limiter/useRateLimiter.js.map +1 -1
- package/dist/throttler/index.cjs +1 -0
- package/dist/throttler/index.d.cts +2 -2
- package/dist/throttler/index.d.ts +2 -2
- package/dist/throttler/useThrottledCallback.cjs.map +1 -1
- package/dist/throttler/useThrottledCallback.d.cts +2 -2
- package/dist/throttler/useThrottledCallback.d.ts +2 -2
- package/dist/throttler/useThrottledCallback.js.map +1 -1
- package/dist/throttler/useThrottledState.cjs.map +1 -1
- package/dist/throttler/useThrottledState.d.cts +3 -3
- package/dist/throttler/useThrottledState.d.ts +3 -3
- package/dist/throttler/useThrottledState.js.map +1 -1
- package/dist/throttler/useThrottledValue.cjs.map +1 -1
- package/dist/throttler/useThrottledValue.d.cts +3 -3
- package/dist/throttler/useThrottledValue.d.ts +3 -3
- package/dist/throttler/useThrottledValue.js.map +1 -1
- package/dist/throttler/useThrottler.cjs +17 -4
- package/dist/throttler/useThrottler.cjs.map +1 -1
- package/dist/throttler/useThrottler.d.cts +21 -2
- package/dist/throttler/useThrottler.d.ts +21 -2
- package/dist/throttler/useThrottler.js +18 -5
- package/dist/throttler/useThrottler.js.map +1 -1
- package/package.json +36 -35
- package/src/async-batcher/useAsyncBatchedCallback.ts +7 -8
- package/src/async-batcher/useAsyncBatcher.ts +51 -7
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +2 -2
- package/src/async-debouncer/useAsyncDebouncer.ts +45 -8
- package/src/async-queuer/useAsyncQueuedState.ts +5 -5
- package/src/async-queuer/useAsyncQueuer.ts +51 -7
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +2 -2
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +37 -6
- package/src/async-throttler/useAsyncThrottledCallback.ts +2 -2
- package/src/async-throttler/useAsyncThrottler.ts +47 -8
- package/src/batcher/useBatchedCallback.ts +6 -10
- package/src/batcher/useBatcher.ts +44 -6
- package/src/debouncer/useDebouncedCallback.ts +2 -2
- package/src/debouncer/useDebouncedState.ts +3 -6
- package/src/debouncer/useDebouncedValue.ts +3 -6
- package/src/debouncer/useDebouncer.ts +38 -8
- package/src/queuer/useQueuedState.ts +3 -3
- package/src/queuer/useQueuedValue.ts +3 -3
- package/src/queuer/useQueuer.ts +44 -6
- package/src/rate-limiter/useRateLimitedCallback.ts +2 -2
- package/src/rate-limiter/useRateLimitedState.ts +6 -6
- package/src/rate-limiter/useRateLimitedValue.ts +6 -6
- package/src/rate-limiter/useRateLimiter.ts +29 -7
- package/src/throttler/useThrottledCallback.ts +2 -2
- package/src/throttler/useThrottledState.ts +3 -6
- package/src/throttler/useThrottledValue.ts +3 -6
- package/src/throttler/useThrottler.ts +38 -8
package/README.md
CHANGED
|
@@ -109,18 +109,18 @@ A lightweight timing and scheduling library for debouncing, throttling, rate lim
|
|
|
109
109
|
<td>
|
|
110
110
|
<a href="https://www.coderabbit.ai/?via=tanstack&dub_id=aCcEEdAOqqutX6OS" >
|
|
111
111
|
<picture>
|
|
112
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/coderabbit-dark-
|
|
113
|
-
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/coderabbit-light-
|
|
114
|
-
<img src="https://tanstack.com/assets/coderabbit-light-
|
|
112
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/coderabbit-dark-D643Zkrv.svg" height="40" />
|
|
113
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/coderabbit-light-CIzGLYU_.svg" height="40" />
|
|
114
|
+
<img src="https://tanstack.com/assets/coderabbit-light-CIzGLYU_.svg" height="40" alt="CodeRabbit" />
|
|
115
115
|
</picture>
|
|
116
116
|
</a>
|
|
117
117
|
</td>
|
|
118
118
|
<td>
|
|
119
119
|
<a href="https://www.cloudflare.com?utm_source=tanstack">
|
|
120
120
|
<picture>
|
|
121
|
-
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/cloudflare-white-
|
|
122
|
-
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/cloudflare-black-
|
|
123
|
-
<img src="https://tanstack.com/assets/cloudflare-black-
|
|
121
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://tanstack.com/assets/cloudflare-white-Co-Tyjbl.svg" height="60" />
|
|
122
|
+
<source media="(prefers-color-scheme: light)" srcset="https://tanstack.com/assets/cloudflare-black-6Ojsn8yh.svg" height="60" />
|
|
123
|
+
<img src="https://tanstack.com/assets/cloudflare-black-6Ojsn8yh.svg" height="60" alt="Cloudflare" />
|
|
124
124
|
</picture>
|
|
125
125
|
</a>
|
|
126
126
|
</td>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PreactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.cjs";
|
|
1
|
+
import { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatcher } from "./useAsyncBatcher.cjs";
|
|
2
2
|
import { useAsyncBatchedCallback } from "./useAsyncBatchedCallback.cjs";
|
|
3
3
|
export * from "@tanstack/pacer/async-batcher";
|
|
4
|
-
export { PreactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
|
|
4
|
+
export { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatchedCallback, useAsyncBatcher };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PreactAsyncBatcher, useAsyncBatcher } from "./useAsyncBatcher.js";
|
|
1
|
+
import { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatcher } from "./useAsyncBatcher.js";
|
|
2
2
|
import { useAsyncBatchedCallback } from "./useAsyncBatchedCallback.js";
|
|
3
3
|
export * from "@tanstack/pacer/async-batcher";
|
|
4
|
-
export { PreactAsyncBatcher, useAsyncBatchedCallback, useAsyncBatcher };
|
|
4
|
+
export { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatchedCallback, useAsyncBatcher };
|
|
@@ -41,8 +41,8 @@ let preact_hooks = require("preact/hooks");
|
|
|
41
41
|
*/
|
|
42
42
|
function useAsyncBatchedCallback(fn, options) {
|
|
43
43
|
const asyncBatchedFn = require_useAsyncBatcher.useAsyncBatcher(fn, options).addItem;
|
|
44
|
-
return (0, preact_hooks.useCallback)(async (
|
|
45
|
-
asyncBatchedFn(
|
|
44
|
+
return (0, preact_hooks.useCallback)(async (item) => {
|
|
45
|
+
await asyncBatchedFn(item);
|
|
46
46
|
}, [asyncBatchedFn]);
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -1 +1 @@
|
|
|
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 {
|
|
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;AACpD,sCACE,OAAO,SAAiB;AACtB,QAAM,eAAe,KAAK;IAE5B,CAAC,eAAe,CACjB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
1
|
+
import { PreactAsyncBatcherOptions } from "./useAsyncBatcher.cjs";
|
|
3
2
|
|
|
4
3
|
//#region src/async-batcher/useAsyncBatchedCallback.d.ts
|
|
5
4
|
/**
|
|
@@ -39,7 +38,7 @@ import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
|
39
38
|
* </button>
|
|
40
39
|
* ```
|
|
41
40
|
*/
|
|
42
|
-
declare function useAsyncBatchedCallback<
|
|
41
|
+
declare function useAsyncBatchedCallback<TValue>(fn: (items: Array<TValue>) => Promise<unknown>, options: PreactAsyncBatcherOptions<TValue, {}>): (item: TValue) => Promise<void>;
|
|
43
42
|
//#endregion
|
|
44
43
|
export { useAsyncBatchedCallback };
|
|
45
44
|
//# sourceMappingURL=useAsyncBatchedCallback.d.cts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
1
|
+
import { PreactAsyncBatcherOptions } from "./useAsyncBatcher.js";
|
|
3
2
|
|
|
4
3
|
//#region src/async-batcher/useAsyncBatchedCallback.d.ts
|
|
5
4
|
/**
|
|
@@ -39,7 +38,7 @@ import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
|
39
38
|
* </button>
|
|
40
39
|
* ```
|
|
41
40
|
*/
|
|
42
|
-
declare function useAsyncBatchedCallback<
|
|
41
|
+
declare function useAsyncBatchedCallback<TValue>(fn: (items: Array<TValue>) => Promise<unknown>, options: PreactAsyncBatcherOptions<TValue, {}>): (item: TValue) => Promise<void>;
|
|
43
42
|
//#endregion
|
|
44
43
|
export { useAsyncBatchedCallback };
|
|
45
44
|
//# sourceMappingURL=useAsyncBatchedCallback.d.ts.map
|
|
@@ -41,8 +41,8 @@ import { useCallback } from "preact/hooks";
|
|
|
41
41
|
*/
|
|
42
42
|
function useAsyncBatchedCallback(fn, options) {
|
|
43
43
|
const asyncBatchedFn = useAsyncBatcher(fn, options).addItem;
|
|
44
|
-
return useCallback(async (
|
|
45
|
-
asyncBatchedFn(
|
|
44
|
+
return useCallback(async (item) => {
|
|
45
|
+
await asyncBatchedFn(item);
|
|
46
46
|
}, [asyncBatchedFn]);
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -1 +1 @@
|
|
|
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 {
|
|
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;AACpD,QAAO,YACL,OAAO,SAAiB;AACtB,QAAM,eAAe,KAAK;IAE5B,CAAC,eAAe,CACjB"}
|
|
@@ -70,6 +70,25 @@ let _tanstack_preact_store = require("@tanstack/preact-store");
|
|
|
70
70
|
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
71
71
|
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
72
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
|
+
*
|
|
73
92
|
* @example
|
|
74
93
|
* ```tsx
|
|
75
94
|
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
@@ -170,14 +189,23 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
170
189
|
const [asyncBatcher] = (0, preact_hooks.useState)(() => {
|
|
171
190
|
const batcherInstance = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
|
|
172
191
|
batcherInstance.Subscribe = function Subscribe(props) {
|
|
173
|
-
const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector);
|
|
192
|
+
const selected = (0, _tanstack_preact_store.useStore)(batcherInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
174
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
175
194
|
};
|
|
176
195
|
return batcherInstance;
|
|
177
196
|
});
|
|
178
197
|
asyncBatcher.fn = fn;
|
|
179
198
|
asyncBatcher.setOptions(mergedOptions);
|
|
180
|
-
|
|
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.useStore)(asyncBatcher.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
181
209
|
return (0, preact_hooks.useMemo)(() => ({
|
|
182
210
|
...asyncBatcher,
|
|
183
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } 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 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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` 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 * @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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\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 = useStore(batcherInstance.store, props.selector)\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 const state = useStore(asyncBatcher.store, selector)\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4MA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,iDAA+B;EACpC,MAAM,kBAAkB,IAAIC,2CAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,gDAAoB,gBAAgB,OAAO,MAAM,SAAS;AAEhE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;CAEtC,MAAM,6CAAiB,aAAa,OAAO,SAAS;AAEpD,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
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, useStore } 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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` 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 = useStore(batcherInstance.store, props.selector, {\n equal: 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 = useStore(asyncBatcher.store, selector, { equal: 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;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,gDAAoB,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAOC,gCACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,mCAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,6CAAiB,aAAa,OAAO,UAAU,EAAE,OAAOA,gCAAS,CAAC;AAExE,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -3,6 +3,13 @@ import { Store } from "@tanstack/preact-store";
|
|
|
3
3
|
import { ComponentChildren } from "preact";
|
|
4
4
|
|
|
5
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
|
+
}
|
|
6
13
|
interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
|
|
7
14
|
/**
|
|
8
15
|
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
|
|
@@ -100,6 +107,25 @@ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<T
|
|
|
100
107
|
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
101
108
|
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
102
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
|
+
*
|
|
103
129
|
* @example
|
|
104
130
|
* ```tsx
|
|
105
131
|
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
@@ -192,7 +218,7 @@ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<T
|
|
|
192
218
|
* const { isExecuting, lastResult, size } = asyncBatcher.state;
|
|
193
219
|
* ```
|
|
194
220
|
*/
|
|
195
|
-
declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?:
|
|
221
|
+
declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: PreactAsyncBatcherOptions<TValue, TSelected>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): PreactAsyncBatcher<TValue, TSelected>;
|
|
196
222
|
//#endregion
|
|
197
|
-
export { PreactAsyncBatcher, useAsyncBatcher };
|
|
223
|
+
export { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatcher };
|
|
198
224
|
//# sourceMappingURL=useAsyncBatcher.d.cts.map
|
|
@@ -3,6 +3,13 @@ import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/
|
|
|
3
3
|
import { Store } from "@tanstack/preact-store";
|
|
4
4
|
|
|
5
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
|
+
}
|
|
6
13
|
interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
|
|
7
14
|
/**
|
|
8
15
|
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async batcher state.
|
|
@@ -100,6 +107,25 @@ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<T
|
|
|
100
107
|
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
101
108
|
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
102
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
|
+
*
|
|
103
129
|
* @example
|
|
104
130
|
* ```tsx
|
|
105
131
|
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
@@ -192,7 +218,7 @@ interface PreactAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<T
|
|
|
192
218
|
* const { isExecuting, lastResult, size } = asyncBatcher.state;
|
|
193
219
|
* ```
|
|
194
220
|
*/
|
|
195
|
-
declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?:
|
|
221
|
+
declare function useAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: PreactAsyncBatcherOptions<TValue, TSelected>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): PreactAsyncBatcher<TValue, TSelected>;
|
|
196
222
|
//#endregion
|
|
197
|
-
export { PreactAsyncBatcher, useAsyncBatcher };
|
|
223
|
+
export { PreactAsyncBatcher, PreactAsyncBatcherOptions, useAsyncBatcher };
|
|
198
224
|
//# sourceMappingURL=useAsyncBatcher.d.ts.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
|
-
import { useMemo, useState } from "preact/hooks";
|
|
2
|
+
import { useEffect, useMemo, useState } from "preact/hooks";
|
|
3
3
|
import { AsyncBatcher } from "@tanstack/pacer/async-batcher";
|
|
4
|
-
import { useStore } from "@tanstack/preact-store";
|
|
4
|
+
import { shallow, useStore } from "@tanstack/preact-store";
|
|
5
5
|
|
|
6
6
|
//#region src/async-batcher/useAsyncBatcher.ts
|
|
7
7
|
/**
|
|
@@ -70,6 +70,25 @@ import { useStore } from "@tanstack/preact-store";
|
|
|
70
70
|
* - `totalItemsProcessed`: Total number of items processed across all batches
|
|
71
71
|
* - `totalItemsFailed`: Total number of items that have failed processing
|
|
72
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
|
+
*
|
|
73
92
|
* @example
|
|
74
93
|
* ```tsx
|
|
75
94
|
* // Basic async batcher for API requests - no reactive state subscriptions
|
|
@@ -170,14 +189,23 @@ function useAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
|
170
189
|
const [asyncBatcher] = useState(() => {
|
|
171
190
|
const batcherInstance = new AsyncBatcher(fn, mergedOptions);
|
|
172
191
|
batcherInstance.Subscribe = function Subscribe(props) {
|
|
173
|
-
const selected = useStore(batcherInstance.store, props.selector);
|
|
192
|
+
const selected = useStore(batcherInstance.store, props.selector, { equal: shallow });
|
|
174
193
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
175
194
|
};
|
|
176
195
|
return batcherInstance;
|
|
177
196
|
});
|
|
178
197
|
asyncBatcher.fn = fn;
|
|
179
198
|
asyncBatcher.setOptions(mergedOptions);
|
|
180
|
-
|
|
199
|
+
useEffect(() => {
|
|
200
|
+
return () => {
|
|
201
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
202
|
+
else {
|
|
203
|
+
asyncBatcher.cancel();
|
|
204
|
+
asyncBatcher.abort();
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}, []);
|
|
208
|
+
const state = useStore(asyncBatcher.store, selector, { equal: shallow });
|
|
181
209
|
return useMemo(() => ({
|
|
182
210
|
...asyncBatcher,
|
|
183
211
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/useAsyncBatcher.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } 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 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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` 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 * @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: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\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 = useStore(batcherInstance.store, props.selector)\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 const state = useStore(asyncBatcher.store, selector)\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4MA,SAAgB,gBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,gBAAgB,eAAe;EACpC,MAAM,kBAAkB,IAAI,aAC1B,IACA,cACD;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,SAAS,gBAAgB,OAAO,MAAM,SAAS;AAEhE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;CAEtC,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
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, useStore } 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 `useStore` hook internally.\n * Although, you can make the state reactive by using the `useStore` 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 = useStore(batcherInstance.store, props.selector, {\n equal: 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 = useStore(asyncBatcher.store, selector, { equal: 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;AAED,kBAAgB,YAAY,SAAS,UAAqB,OAGvD;GACD,MAAM,WAAW,SAAS,gBAAgB,OAAO,MAAM,UAAU,EAC/D,OAAO,SACR,CAAC;AAEF,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,cAAa,KAAK;AAClB,cAAa,WAAW,cAAc;AAGtC,iBAAgB;AACd,eAAa;AACX,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;;IAGvB,EAAE,CAAC;CAGN,MAAM,QAAQ,SAAS,aAAa,OAAO,UAAU,EAAE,OAAO,SAAS,CAAC;AAExE,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,cAAc,MAAM,CACtB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PreactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.cjs";
|
|
1
|
+
import { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncer } from "./useAsyncDebouncer.cjs";
|
|
2
2
|
import { useAsyncDebouncedCallback } from "./useAsyncDebouncedCallback.cjs";
|
|
3
3
|
export * from "@tanstack/pacer/async-debouncer";
|
|
4
|
-
export { PreactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
|
|
4
|
+
export { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncedCallback, useAsyncDebouncer };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { PreactAsyncDebouncer, useAsyncDebouncer } from "./useAsyncDebouncer.js";
|
|
1
|
+
import { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncer } from "./useAsyncDebouncer.js";
|
|
2
2
|
import { useAsyncDebouncedCallback } from "./useAsyncDebouncedCallback.js";
|
|
3
3
|
export * from "@tanstack/pacer/async-debouncer";
|
|
4
|
-
export { PreactAsyncDebouncer, useAsyncDebouncedCallback, useAsyncDebouncer };
|
|
4
|
+
export { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncedCallback, useAsyncDebouncer };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncedCallback.cjs","names":["useAsyncDebouncer"],"sources":["../../src/async-debouncer/useAsyncDebouncedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncDebouncer } from './useAsyncDebouncer'\nimport type {
|
|
1
|
+
{"version":3,"file":"useAsyncDebouncedCallback.cjs","names":["useAsyncDebouncer"],"sources":["../../src/async-debouncer/useAsyncDebouncedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncDebouncer } from './useAsyncDebouncer'\nimport type { PreactAsyncDebouncerOptions } from './useAsyncDebouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\n/**\n * A Preact hook that creates a debounced version of an async callback function.\n * This hook is a convenient wrapper around the `useAsyncDebouncer` hook,\n * providing a stable, debounced async function reference for use in Preact components.\n *\n * The debounced async function will only execute after the specified wait time has elapsed\n * since its last invocation. If called again before the wait time expires, the timer\n * resets and starts waiting again. The returned function always returns a promise\n * that resolves or rejects with the result of the original async function.\n *\n * This hook provides a simpler API compared to `useAsyncDebouncer`, making it ideal for basic\n * async debouncing needs. However, it does not expose the underlying AsyncDebouncer instance.\n *\n * For advanced usage requiring features like:\n * - Manual cancellation\n * - Access to execution/error state\n * - Custom useCallback dependencies\n *\n * Consider using the `useAsyncDebouncer` hook instead.\n *\n *\n * @example\n * ```tsx\n * // Debounce an async search handler\n * const handleSearch = useAsyncDebouncedCallback(async (query: string) => {\n * const results = await fetchSearchResults(query);\n * return results;\n * }, {\n * wait: 500 // Wait 500ms between executions\n * });\n *\n * // Use in an input\n * <input\n * type=\"search\"\n * onChange={e => handleSearch(e.target.value)}\n * />\n * ```\n */\nexport function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, {}>,\n): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>> {\n const asyncDebouncedFn = useAsyncDebouncer(fn, options).maybeExecute\n return useCallback(\n (...args: Parameters<TFn>) =>\n asyncDebouncedFn(...args) as Promise<ReturnType<TFn>>,\n [asyncDebouncedFn],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,0BACd,IACA,SACwD;CACxD,MAAM,mBAAmBA,4CAAkB,IAAI,QAAQ,CAAC;AACxD,uCACG,GAAG,SACF,iBAAiB,GAAG,KAAK,EAC3B,CAAC,iBAAiB,CACnB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { PreactAsyncDebouncerOptions } from "./useAsyncDebouncer.cjs";
|
|
1
2
|
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
2
|
-
import { AsyncDebouncerOptions } from "@tanstack/pacer/async-debouncer";
|
|
3
3
|
|
|
4
4
|
//#region src/async-debouncer/useAsyncDebouncedCallback.d.ts
|
|
5
5
|
/**
|
|
@@ -40,7 +40,7 @@ import { AsyncDebouncerOptions } from "@tanstack/pacer/async-debouncer";
|
|
|
40
40
|
* />
|
|
41
41
|
* ```
|
|
42
42
|
*/
|
|
43
|
-
declare function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(fn: TFn, options:
|
|
43
|
+
declare function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(fn: TFn, options: PreactAsyncDebouncerOptions<TFn, {}>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>>;
|
|
44
44
|
//#endregion
|
|
45
45
|
export { useAsyncDebouncedCallback };
|
|
46
46
|
//# sourceMappingURL=useAsyncDebouncedCallback.d.cts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { PreactAsyncDebouncerOptions } from "./useAsyncDebouncer.js";
|
|
2
2
|
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
3
3
|
|
|
4
4
|
//#region src/async-debouncer/useAsyncDebouncedCallback.d.ts
|
|
@@ -40,7 +40,7 @@ import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
|
40
40
|
* />
|
|
41
41
|
* ```
|
|
42
42
|
*/
|
|
43
|
-
declare function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(fn: TFn, options:
|
|
43
|
+
declare function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(fn: TFn, options: PreactAsyncDebouncerOptions<TFn, {}>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>>;
|
|
44
44
|
//#endregion
|
|
45
45
|
export { useAsyncDebouncedCallback };
|
|
46
46
|
//# sourceMappingURL=useAsyncDebouncedCallback.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncedCallback.js","names":[],"sources":["../../src/async-debouncer/useAsyncDebouncedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncDebouncer } from './useAsyncDebouncer'\nimport type {
|
|
1
|
+
{"version":3,"file":"useAsyncDebouncedCallback.js","names":[],"sources":["../../src/async-debouncer/useAsyncDebouncedCallback.ts"],"sourcesContent":["import { useCallback } from 'preact/hooks'\nimport { useAsyncDebouncer } from './useAsyncDebouncer'\nimport type { PreactAsyncDebouncerOptions } from './useAsyncDebouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\n/**\n * A Preact hook that creates a debounced version of an async callback function.\n * This hook is a convenient wrapper around the `useAsyncDebouncer` hook,\n * providing a stable, debounced async function reference for use in Preact components.\n *\n * The debounced async function will only execute after the specified wait time has elapsed\n * since its last invocation. If called again before the wait time expires, the timer\n * resets and starts waiting again. The returned function always returns a promise\n * that resolves or rejects with the result of the original async function.\n *\n * This hook provides a simpler API compared to `useAsyncDebouncer`, making it ideal for basic\n * async debouncing needs. However, it does not expose the underlying AsyncDebouncer instance.\n *\n * For advanced usage requiring features like:\n * - Manual cancellation\n * - Access to execution/error state\n * - Custom useCallback dependencies\n *\n * Consider using the `useAsyncDebouncer` hook instead.\n *\n *\n * @example\n * ```tsx\n * // Debounce an async search handler\n * const handleSearch = useAsyncDebouncedCallback(async (query: string) => {\n * const results = await fetchSearchResults(query);\n * return results;\n * }, {\n * wait: 500 // Wait 500ms between executions\n * });\n *\n * // Use in an input\n * <input\n * type=\"search\"\n * onChange={e => handleSearch(e.target.value)}\n * />\n * ```\n */\nexport function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, {}>,\n): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>> {\n const asyncDebouncedFn = useAsyncDebouncer(fn, options).maybeExecute\n return useCallback(\n (...args: Parameters<TFn>) =>\n asyncDebouncedFn(...args) as Promise<ReturnType<TFn>>,\n [asyncDebouncedFn],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,SAAgB,0BACd,IACA,SACwD;CACxD,MAAM,mBAAmB,kBAAkB,IAAI,QAAQ,CAAC;AACxD,QAAO,aACJ,GAAG,SACF,iBAAiB,GAAG,KAAK,EAC3B,CAAC,iBAAiB,CACnB"}
|
|
@@ -60,6 +60,24 @@ let _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer")
|
|
|
60
60
|
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
61
61
|
* - `successCount`: Number of function executions that have completed successfully
|
|
62
62
|
*
|
|
63
|
+
* ## Unmount behavior
|
|
64
|
+
*
|
|
65
|
+
* By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.
|
|
66
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
67
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
68
|
+
*
|
|
69
|
+
* ```tsx
|
|
70
|
+
* const debouncer = useAsyncDebouncer(fn, {
|
|
71
|
+
* wait: 500,
|
|
72
|
+
* onUnmount: (d) => d.flush()
|
|
73
|
+
* });
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
77
|
+
* If your debounced function updates Preact state, those updates may run after the component has
|
|
78
|
+
* unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
|
|
79
|
+
* accordingly when using onUnmount with flush.
|
|
80
|
+
*
|
|
63
81
|
* @example
|
|
64
82
|
* ```tsx
|
|
65
83
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -149,19 +167,23 @@ function useAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
149
167
|
const [asyncDebouncer] = (0, preact_hooks.useState)(() => {
|
|
150
168
|
const debouncerInstance = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
|
|
151
169
|
debouncerInstance.Subscribe = function Subscribe(props) {
|
|
152
|
-
const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector);
|
|
170
|
+
const selected = (0, _tanstack_preact_store.useStore)(debouncerInstance.store, props.selector, { equal: _tanstack_preact_store.shallow });
|
|
153
171
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
154
172
|
};
|
|
155
173
|
return debouncerInstance;
|
|
156
174
|
});
|
|
157
175
|
asyncDebouncer.fn = fn;
|
|
158
176
|
asyncDebouncer.setOptions(mergedOptions);
|
|
159
|
-
const state = (0, _tanstack_preact_store.useStore)(asyncDebouncer.store, selector);
|
|
177
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncDebouncer.store, selector, { equal: _tanstack_preact_store.shallow });
|
|
160
178
|
(0, preact_hooks.useEffect)(() => {
|
|
161
179
|
return () => {
|
|
162
|
-
|
|
180
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
181
|
+
else {
|
|
182
|
+
asyncDebouncer.cancel();
|
|
183
|
+
asyncDebouncer.abort();
|
|
184
|
+
}
|
|
163
185
|
};
|
|
164
|
-
}, [
|
|
186
|
+
}, []);
|
|
165
187
|
return (0, preact_hooks.useMemo)(() => ({
|
|
166
188
|
...asyncDebouncer,
|
|
167
189
|
state
|