@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,50 +0,0 @@
|
|
|
1
|
-
const require_useAsyncDebouncer = require('./useAsyncDebouncer.cjs');
|
|
2
|
-
let preact_hooks = require("preact/hooks");
|
|
3
|
-
|
|
4
|
-
//#region src/async-debouncer/useAsyncDebouncedCallback.ts
|
|
5
|
-
/**
|
|
6
|
-
* A Preact hook that creates a debounced version of an async callback function.
|
|
7
|
-
* This hook is a convenient wrapper around the `useAsyncDebouncer` hook,
|
|
8
|
-
* providing a stable, debounced async function reference for use in Preact components.
|
|
9
|
-
*
|
|
10
|
-
* The debounced async function will only execute after the specified wait time has elapsed
|
|
11
|
-
* since its last invocation. If called again before the wait time expires, the timer
|
|
12
|
-
* resets and starts waiting again. The returned function always returns a promise
|
|
13
|
-
* that resolves or rejects with the result of the original async function.
|
|
14
|
-
*
|
|
15
|
-
* This hook provides a simpler API compared to `useAsyncDebouncer`, making it ideal for basic
|
|
16
|
-
* async debouncing needs. However, it does not expose the underlying AsyncDebouncer instance.
|
|
17
|
-
*
|
|
18
|
-
* For advanced usage requiring features like:
|
|
19
|
-
* - Manual cancellation
|
|
20
|
-
* - Access to execution/error state
|
|
21
|
-
* - Custom useCallback dependencies
|
|
22
|
-
*
|
|
23
|
-
* Consider using the `useAsyncDebouncer` hook instead.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```tsx
|
|
28
|
-
* // Debounce an async search handler
|
|
29
|
-
* const handleSearch = useAsyncDebouncedCallback(async (query: string) => {
|
|
30
|
-
* const results = await fetchSearchResults(query);
|
|
31
|
-
* return results;
|
|
32
|
-
* }, {
|
|
33
|
-
* wait: 500 // Wait 500ms between executions
|
|
34
|
-
* });
|
|
35
|
-
*
|
|
36
|
-
* // Use in an input
|
|
37
|
-
* <input
|
|
38
|
-
* type="search"
|
|
39
|
-
* onChange={e => handleSearch(e.target.value)}
|
|
40
|
-
* />
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
function useAsyncDebouncedCallback(fn, options) {
|
|
44
|
-
const asyncDebouncedFn = require_useAsyncDebouncer.useAsyncDebouncer(fn, options).maybeExecute;
|
|
45
|
-
return (0, preact_hooks.useCallback)((...args) => asyncDebouncedFn(...args), [asyncDebouncedFn]);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
//#endregion
|
|
49
|
-
exports.useAsyncDebouncedCallback = useAsyncDebouncedCallback;
|
|
50
|
-
//# sourceMappingURL=useAsyncDebouncedCallback.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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;CACxD,sCACG,GAAG,SACF,iBAAiB,GAAG,KAAK,EAC3B,CAAC,iBAAiB,CACnB"}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { PreactAsyncDebouncerOptions } from "./useAsyncDebouncer.cjs";
|
|
2
|
-
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
3
|
-
|
|
4
|
-
//#region src/async-debouncer/useAsyncDebouncedCallback.d.ts
|
|
5
|
-
/**
|
|
6
|
-
* A Preact hook that creates a debounced version of an async callback function.
|
|
7
|
-
* This hook is a convenient wrapper around the `useAsyncDebouncer` hook,
|
|
8
|
-
* providing a stable, debounced async function reference for use in Preact components.
|
|
9
|
-
*
|
|
10
|
-
* The debounced async function will only execute after the specified wait time has elapsed
|
|
11
|
-
* since its last invocation. If called again before the wait time expires, the timer
|
|
12
|
-
* resets and starts waiting again. The returned function always returns a promise
|
|
13
|
-
* that resolves or rejects with the result of the original async function.
|
|
14
|
-
*
|
|
15
|
-
* This hook provides a simpler API compared to `useAsyncDebouncer`, making it ideal for basic
|
|
16
|
-
* async debouncing needs. However, it does not expose the underlying AsyncDebouncer instance.
|
|
17
|
-
*
|
|
18
|
-
* For advanced usage requiring features like:
|
|
19
|
-
* - Manual cancellation
|
|
20
|
-
* - Access to execution/error state
|
|
21
|
-
* - Custom useCallback dependencies
|
|
22
|
-
*
|
|
23
|
-
* Consider using the `useAsyncDebouncer` hook instead.
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```tsx
|
|
28
|
-
* // Debounce an async search handler
|
|
29
|
-
* const handleSearch = useAsyncDebouncedCallback(async (query: string) => {
|
|
30
|
-
* const results = await fetchSearchResults(query);
|
|
31
|
-
* return results;
|
|
32
|
-
* }, {
|
|
33
|
-
* wait: 500 // Wait 500ms between executions
|
|
34
|
-
* });
|
|
35
|
-
*
|
|
36
|
-
* // Use in an input
|
|
37
|
-
* <input
|
|
38
|
-
* type="search"
|
|
39
|
-
* onChange={e => handleSearch(e.target.value)}
|
|
40
|
-
* />
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
declare function useAsyncDebouncedCallback<TFn extends AnyAsyncFunction>(fn: TFn, options: PreactAsyncDebouncerOptions<TFn, {}>): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>>;
|
|
44
|
-
//#endregion
|
|
45
|
-
export { useAsyncDebouncedCallback };
|
|
46
|
-
//# sourceMappingURL=useAsyncDebouncedCallback.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
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;CACxD,OAAO,aACJ,GAAG,SACF,iBAAiB,GAAG,KAAK,EAC3B,CAAC,iBAAiB,CACnB"}
|
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
|
-
let preact_hooks = require("preact/hooks");
|
|
3
|
-
let _tanstack_preact_store = require("@tanstack/preact-store");
|
|
4
|
-
let _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer");
|
|
5
|
-
|
|
6
|
-
//#region src/async-debouncer/useAsyncDebouncer.ts
|
|
7
|
-
/**
|
|
8
|
-
* A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.
|
|
9
|
-
*
|
|
10
|
-
* This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that
|
|
11
|
-
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
12
|
-
*
|
|
13
|
-
* Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.
|
|
14
|
-
* Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
|
|
15
|
-
* or input changes where you only want to execute the handler after the events have stopped occurring.
|
|
16
|
-
*
|
|
17
|
-
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
18
|
-
* the function stops being called for the specified delay period.
|
|
19
|
-
*
|
|
20
|
-
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
21
|
-
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
22
|
-
* instead of setting the result on a state variable from within the debounced function.
|
|
23
|
-
*
|
|
24
|
-
* Error Handling:
|
|
25
|
-
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
|
|
26
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
27
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
28
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
29
|
-
* - The error state can be checked using the underlying AsyncDebouncer instance
|
|
30
|
-
*
|
|
31
|
-
* ## State Management and Selector
|
|
32
|
-
*
|
|
33
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
34
|
-
* in two ways:
|
|
35
|
-
*
|
|
36
|
-
* **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
37
|
-
*
|
|
38
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
39
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
40
|
-
* in child components.
|
|
41
|
-
*
|
|
42
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
43
|
-
*
|
|
44
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
45
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
46
|
-
* state changes occur.
|
|
47
|
-
*
|
|
48
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
49
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
50
|
-
* re-renders and gives you full control over when your component updates.
|
|
51
|
-
*
|
|
52
|
-
* Available state properties:
|
|
53
|
-
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
54
|
-
* - `errorCount`: Number of function executions that have resulted in errors
|
|
55
|
-
* - `isExecuting`: Whether the debounced function is currently executing asynchronously
|
|
56
|
-
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
57
|
-
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
58
|
-
* - `lastResult`: The result from the most recent successful function execution
|
|
59
|
-
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
60
|
-
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
61
|
-
* - `successCount`: Number of function executions that have completed successfully
|
|
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
|
-
*
|
|
81
|
-
* @example
|
|
82
|
-
* ```tsx
|
|
83
|
-
* // Default behavior - no reactive state subscriptions
|
|
84
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
85
|
-
* async (query: string) => {
|
|
86
|
-
* const results = await api.search(query);
|
|
87
|
-
* return results;
|
|
88
|
-
* },
|
|
89
|
-
* { wait: 500 }
|
|
90
|
-
* );
|
|
91
|
-
*
|
|
92
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
93
|
-
* <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
94
|
-
* {({ isPending }) => (
|
|
95
|
-
* <div>{isPending ? 'Searching...' : 'Ready'}</div>
|
|
96
|
-
* )}
|
|
97
|
-
* </searchDebouncer.Subscribe>
|
|
98
|
-
*
|
|
99
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
100
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
101
|
-
* async (query: string) => {
|
|
102
|
-
* const results = await api.search(query);
|
|
103
|
-
* return results;
|
|
104
|
-
* },
|
|
105
|
-
* { wait: 500 },
|
|
106
|
-
* (state) => ({
|
|
107
|
-
* isExecuting: state.isExecuting,
|
|
108
|
-
* isPending: state.isPending
|
|
109
|
-
* })
|
|
110
|
-
* );
|
|
111
|
-
*
|
|
112
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
113
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
114
|
-
* async (query: string) => {
|
|
115
|
-
* const results = await api.search(query);
|
|
116
|
-
* return results;
|
|
117
|
-
* },
|
|
118
|
-
* { wait: 500 },
|
|
119
|
-
* (state) => ({
|
|
120
|
-
* lastResult: state.lastResult,
|
|
121
|
-
* successCount: state.successCount
|
|
122
|
-
* })
|
|
123
|
-
* );
|
|
124
|
-
*
|
|
125
|
-
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
126
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
127
|
-
* async (query: string) => {
|
|
128
|
-
* const results = await api.search(query);
|
|
129
|
-
* return results;
|
|
130
|
-
* },
|
|
131
|
-
* {
|
|
132
|
-
* wait: 500,
|
|
133
|
-
* onError: (error) => console.error('Search failed:', error)
|
|
134
|
-
* },
|
|
135
|
-
* (state) => ({
|
|
136
|
-
* errorCount: state.errorCount,
|
|
137
|
-
* status: state.status
|
|
138
|
-
* })
|
|
139
|
-
* );
|
|
140
|
-
*
|
|
141
|
-
* // With state management
|
|
142
|
-
* const [results, setResults] = useState([]);
|
|
143
|
-
* const { maybeExecute, state } = useAsyncDebouncer(
|
|
144
|
-
* async (searchTerm) => {
|
|
145
|
-
* const data = await searchAPI(searchTerm);
|
|
146
|
-
* setResults(data);
|
|
147
|
-
* },
|
|
148
|
-
* {
|
|
149
|
-
* wait: 300,
|
|
150
|
-
* leading: true, // Execute immediately on first call
|
|
151
|
-
* trailing: false, // Skip trailing edge updates
|
|
152
|
-
* onError: (error) => {
|
|
153
|
-
* console.error('API call failed:', error);
|
|
154
|
-
* }
|
|
155
|
-
* }
|
|
156
|
-
* );
|
|
157
|
-
*
|
|
158
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
159
|
-
* const { isExecuting, lastResult } = state;
|
|
160
|
-
* ```
|
|
161
|
-
*/
|
|
162
|
-
function useAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
163
|
-
const mergedOptions = {
|
|
164
|
-
...require_PacerProvider.useDefaultPacerOptions().asyncDebouncer,
|
|
165
|
-
...options
|
|
166
|
-
};
|
|
167
|
-
const [asyncDebouncer] = (0, preact_hooks.useState)(() => {
|
|
168
|
-
const debouncerInstance = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
|
|
169
|
-
debouncerInstance.Subscribe = function Subscribe(props) {
|
|
170
|
-
const selected = (0, _tanstack_preact_store.useSelector)(debouncerInstance.store, props.selector, { compare: _tanstack_preact_store.shallow });
|
|
171
|
-
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
172
|
-
};
|
|
173
|
-
return debouncerInstance;
|
|
174
|
-
});
|
|
175
|
-
asyncDebouncer.fn = fn;
|
|
176
|
-
asyncDebouncer.setOptions(mergedOptions);
|
|
177
|
-
const state = (0, _tanstack_preact_store.useSelector)(asyncDebouncer.store, selector, { compare: _tanstack_preact_store.shallow });
|
|
178
|
-
(0, preact_hooks.useEffect)(() => {
|
|
179
|
-
return () => {
|
|
180
|
-
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
181
|
-
else {
|
|
182
|
-
asyncDebouncer.cancel();
|
|
183
|
-
asyncDebouncer.abort();
|
|
184
|
-
}
|
|
185
|
-
};
|
|
186
|
-
}, []);
|
|
187
|
-
return (0, preact_hooks.useMemo)(() => ({
|
|
188
|
-
...asyncDebouncer,
|
|
189
|
-
state
|
|
190
|
-
}), [asyncDebouncer, state]);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
//#endregion
|
|
194
|
-
exports.useAsyncDebouncer = useAsyncDebouncer;
|
|
195
|
-
//# sourceMappingURL=useAsyncDebouncer.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer","shallow"],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer 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 `debouncer.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 * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution 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 debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(debouncerInstance.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 debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useSelector(asyncDebouncer.store, selector, {\n compare: shallow,\n })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;EAED,kBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,mDAAuB,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAASC,gCACV,CAAC;GAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;EAGZ,OAAO;GACP;CAEF,eAAe,KAAK;CACpB,eAAe,WAAW,cAAc;CAExC,MAAM,gDAAoB,eAAe,OAAO,UAAU,EACxD,SAASA,gCACV,CAAC;CAGF,kCAAgB;EACd,aAAa;GACX,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;;IAGzB,EAAE,CAAC;CAGN,wCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
@@ -1,203 +0,0 @@
|
|
|
1
|
-
import { Store } from "@tanstack/preact-store";
|
|
2
|
-
import { ComponentChildren } from "preact";
|
|
3
|
-
import { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState } from "@tanstack/pacer/async-debouncer";
|
|
4
|
-
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
5
|
-
|
|
6
|
-
//#region src/async-debouncer/useAsyncDebouncer.d.ts
|
|
7
|
-
interface PreactAsyncDebouncerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncDebouncerOptions<TFn> {
|
|
8
|
-
/**
|
|
9
|
-
* Optional callback invoked when the component unmounts. Receives the debouncer instance.
|
|
10
|
-
* When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
|
|
11
|
-
*/
|
|
12
|
-
onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void;
|
|
13
|
-
}
|
|
14
|
-
interface PreactAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncDebouncer<TFn>, 'store'> {
|
|
15
|
-
/**
|
|
16
|
-
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.
|
|
17
|
-
*
|
|
18
|
-
* This is useful for opting into state re-renders for specific parts of the debouncer state
|
|
19
|
-
* deep in your component tree without needing to pass a selector to the hook.
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
23
|
-
* {({ isPending }) => (
|
|
24
|
-
* <div>{isPending ? 'Loading...' : 'Ready'}</div>
|
|
25
|
-
* )}
|
|
26
|
-
* </debouncer.Subscribe>
|
|
27
|
-
*/
|
|
28
|
-
Subscribe: <TSelected>(props: {
|
|
29
|
-
selector: (state: AsyncDebouncerState<TFn>) => TSelected;
|
|
30
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
|
|
31
|
-
}) => ComponentChildren;
|
|
32
|
-
/**
|
|
33
|
-
* Reactive state that will be updated and re-rendered when the debouncer state changes
|
|
34
|
-
*
|
|
35
|
-
* Use this instead of `debouncer.store.state`
|
|
36
|
-
*/
|
|
37
|
-
readonly state: Readonly<TSelected>;
|
|
38
|
-
/**
|
|
39
|
-
* @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.
|
|
40
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
41
|
-
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
42
|
-
*/
|
|
43
|
-
readonly store: Store<Readonly<AsyncDebouncerState<TFn>>>;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.
|
|
47
|
-
*
|
|
48
|
-
* This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that
|
|
49
|
-
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
50
|
-
*
|
|
51
|
-
* Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.
|
|
52
|
-
* Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
|
|
53
|
-
* or input changes where you only want to execute the handler after the events have stopped occurring.
|
|
54
|
-
*
|
|
55
|
-
* Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
|
|
56
|
-
* the function stops being called for the specified delay period.
|
|
57
|
-
*
|
|
58
|
-
* Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
|
|
59
|
-
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
60
|
-
* instead of setting the result on a state variable from within the debounced function.
|
|
61
|
-
*
|
|
62
|
-
* Error Handling:
|
|
63
|
-
* - If an `onError` handler is provided, it will be called with the error and debouncer instance
|
|
64
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
65
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
66
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
67
|
-
* - The error state can be checked using the underlying AsyncDebouncer instance
|
|
68
|
-
*
|
|
69
|
-
* ## State Management and Selector
|
|
70
|
-
*
|
|
71
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
72
|
-
* in two ways:
|
|
73
|
-
*
|
|
74
|
-
* **1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
75
|
-
*
|
|
76
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
77
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
78
|
-
* in child components.
|
|
79
|
-
*
|
|
80
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
81
|
-
*
|
|
82
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
83
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
84
|
-
* state changes occur.
|
|
85
|
-
*
|
|
86
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
87
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
88
|
-
* re-renders and gives you full control over when your component updates.
|
|
89
|
-
*
|
|
90
|
-
* Available state properties:
|
|
91
|
-
* - `canLeadingExecute`: Whether the debouncer can execute on the leading edge
|
|
92
|
-
* - `errorCount`: Number of function executions that have resulted in errors
|
|
93
|
-
* - `isExecuting`: Whether the debounced function is currently executing asynchronously
|
|
94
|
-
* - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
|
|
95
|
-
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
96
|
-
* - `lastResult`: The result from the most recent successful function execution
|
|
97
|
-
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
98
|
-
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
99
|
-
* - `successCount`: Number of function executions that have completed successfully
|
|
100
|
-
*
|
|
101
|
-
* ## Unmount behavior
|
|
102
|
-
*
|
|
103
|
-
* By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.
|
|
104
|
-
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
105
|
-
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
106
|
-
*
|
|
107
|
-
* ```tsx
|
|
108
|
-
* const debouncer = useAsyncDebouncer(fn, {
|
|
109
|
-
* wait: 500,
|
|
110
|
-
* onUnmount: (d) => d.flush()
|
|
111
|
-
* });
|
|
112
|
-
* ```
|
|
113
|
-
*
|
|
114
|
-
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
115
|
-
* If your debounced function updates Preact state, those updates may run after the component has
|
|
116
|
-
* unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
|
|
117
|
-
* accordingly when using onUnmount with flush.
|
|
118
|
-
*
|
|
119
|
-
* @example
|
|
120
|
-
* ```tsx
|
|
121
|
-
* // Default behavior - no reactive state subscriptions
|
|
122
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
123
|
-
* async (query: string) => {
|
|
124
|
-
* const results = await api.search(query);
|
|
125
|
-
* return results;
|
|
126
|
-
* },
|
|
127
|
-
* { wait: 500 }
|
|
128
|
-
* );
|
|
129
|
-
*
|
|
130
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
131
|
-
* <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
132
|
-
* {({ isPending }) => (
|
|
133
|
-
* <div>{isPending ? 'Searching...' : 'Ready'}</div>
|
|
134
|
-
* )}
|
|
135
|
-
* </searchDebouncer.Subscribe>
|
|
136
|
-
*
|
|
137
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
138
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
139
|
-
* async (query: string) => {
|
|
140
|
-
* const results = await api.search(query);
|
|
141
|
-
* return results;
|
|
142
|
-
* },
|
|
143
|
-
* { wait: 500 },
|
|
144
|
-
* (state) => ({
|
|
145
|
-
* isExecuting: state.isExecuting,
|
|
146
|
-
* isPending: state.isPending
|
|
147
|
-
* })
|
|
148
|
-
* );
|
|
149
|
-
*
|
|
150
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
151
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
152
|
-
* async (query: string) => {
|
|
153
|
-
* const results = await api.search(query);
|
|
154
|
-
* return results;
|
|
155
|
-
* },
|
|
156
|
-
* { wait: 500 },
|
|
157
|
-
* (state) => ({
|
|
158
|
-
* lastResult: state.lastResult,
|
|
159
|
-
* successCount: state.successCount
|
|
160
|
-
* })
|
|
161
|
-
* );
|
|
162
|
-
*
|
|
163
|
-
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
164
|
-
* const searchDebouncer = useAsyncDebouncer(
|
|
165
|
-
* async (query: string) => {
|
|
166
|
-
* const results = await api.search(query);
|
|
167
|
-
* return results;
|
|
168
|
-
* },
|
|
169
|
-
* {
|
|
170
|
-
* wait: 500,
|
|
171
|
-
* onError: (error) => console.error('Search failed:', error)
|
|
172
|
-
* },
|
|
173
|
-
* (state) => ({
|
|
174
|
-
* errorCount: state.errorCount,
|
|
175
|
-
* status: state.status
|
|
176
|
-
* })
|
|
177
|
-
* );
|
|
178
|
-
*
|
|
179
|
-
* // With state management
|
|
180
|
-
* const [results, setResults] = useState([]);
|
|
181
|
-
* const { maybeExecute, state } = useAsyncDebouncer(
|
|
182
|
-
* async (searchTerm) => {
|
|
183
|
-
* const data = await searchAPI(searchTerm);
|
|
184
|
-
* setResults(data);
|
|
185
|
-
* },
|
|
186
|
-
* {
|
|
187
|
-
* wait: 300,
|
|
188
|
-
* leading: true, // Execute immediately on first call
|
|
189
|
-
* trailing: false, // Skip trailing edge updates
|
|
190
|
-
* onError: (error) => {
|
|
191
|
-
* console.error('API call failed:', error);
|
|
192
|
-
* }
|
|
193
|
-
* }
|
|
194
|
-
* );
|
|
195
|
-
*
|
|
196
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
197
|
-
* const { isExecuting, lastResult } = state;
|
|
198
|
-
* ```
|
|
199
|
-
*/
|
|
200
|
-
declare function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: PreactAsyncDebouncerOptions<TFn, TSelected>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): PreactAsyncDebouncer<TFn, TSelected>;
|
|
201
|
-
//#endregion
|
|
202
|
-
export { PreactAsyncDebouncer, PreactAsyncDebouncerOptions, useAsyncDebouncer };
|
|
203
|
-
//# sourceMappingURL=useAsyncDebouncer.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useAsyncDebouncer.js","names":[],"sources":["../../src/async-debouncer/useAsyncDebouncer.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { shallow, useSelector } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: PreactAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface PreactAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async debouncer state.\n *\n * This is useful for opting into state re-renders for specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer 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 AsyncDebouncer 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 `debouncer.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 * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the debounced function is currently executing asynchronously\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastResult`: The result from the most recent successful function execution\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * ## Unmount behavior\n *\n * By default, the hook cancels any pending execution 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 debouncer = useAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced 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 * // Default behavior - no reactive state subscriptions\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Searching...' : 'Ready'}</div>\n * )}\n * </searchDebouncer.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * isExecuting: state.isExecuting,\n * isPending: state.isPending\n * })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const searchDebouncer = useAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * {\n * wait: 500,\n * onError: (error) => console.error('Search failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // With state management\n * const [results, setResults] = useState([]);\n * const { maybeExecute, state } = useAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * setResults(data);\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: PreactAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as PreactAsyncDebouncerOptions<TFn, TSelected>\n const [asyncDebouncer] = useState(() => {\n const debouncerInstance = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncDebouncer<TFn, TSelected>\n\n debouncerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useSelector(debouncerInstance.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 debouncerInstance\n })\n\n asyncDebouncer.fn = fn\n asyncDebouncer.setOptions(mergedOptions)\n\n const state = useSelector(asyncDebouncer.store, selector, {\n compare: shallow,\n })\n\n /* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */\n useEffect(() => {\n return () => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n }\n }, [])\n /* eslint-enable react-hooks/exhaustive-deps */\n\n return useMemo(\n () =>\n ({\n ...asyncDebouncer,\n state,\n }) as PreactAsyncDebouncer<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncDebouncer, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;EAED,kBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,YAAY,kBAAkB,OAAO,MAAM,UAAU,EACpE,SAAS,SACV,CAAC;GAEF,OAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;EAGZ,OAAO;GACP;CAEF,eAAe,KAAK;CACpB,eAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,YAAY,eAAe,OAAO,UAAU,EACxD,SAAS,SACV,CAAC;CAGF,gBAAgB;EACd,aAAa;GACX,IAAI,cAAc,WAChB,cAAc,UAAU,eAAe;QAClC;IACL,eAAe,QAAQ;IACvB,eAAe,OAAO;;;IAGzB,EAAE,CAAC;CAGN,OAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const require_useAsyncQueuer = require('./useAsyncQueuer.cjs');
|
|
3
|
-
const require_useAsyncQueuedState = require('./useAsyncQueuedState.cjs');
|
|
4
|
-
|
|
5
|
-
exports.useAsyncQueuedState = require_useAsyncQueuedState.useAsyncQueuedState;
|
|
6
|
-
exports.useAsyncQueuer = require_useAsyncQueuer.useAsyncQueuer;
|
|
7
|
-
var _tanstack_pacer_async_queuer = require("@tanstack/pacer/async-queuer");
|
|
8
|
-
Object.keys(_tanstack_pacer_async_queuer).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_queuer[k]; }
|
|
12
|
-
});
|
|
13
|
-
});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { PreactAsyncQueuer, PreactAsyncQueuerOptions, useAsyncQueuer } from "./useAsyncQueuer.cjs";
|
|
2
|
-
import { useAsyncQueuedState } from "./useAsyncQueuedState.cjs";
|
|
3
|
-
export * from "@tanstack/pacer/async-queuer";
|
|
4
|
-
export { PreactAsyncQueuer, PreactAsyncQueuerOptions, useAsyncQueuedState, useAsyncQueuer };
|