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