Open History to see the last commit
1---
2id: useAsyncBatcher
3title: useAsyncBatcher
4---
5
6```ts
7function useAsyncBatcher<TValue, TSelected>(
8 fn,
9 options?,
10selector?): PreactAsyncBatcher<TValue, TSelected>;
11```
12
13Defined in: [async-batcher/useAsyncBatcher.ts:234](https://github.com/TanStack/pacer/blob/main/packages/preact-pacer/src/async-batcher/useAsyncBatcher.ts#L234)
14
15A Preact hook that creates an `AsyncBatcher` instance for managing asynchronous batches of items.
16
17This is the async version of the useBatcher hook. Unlike the sync version, this async batcher:
18- Handles promises and returns results from batch executions
19- Provides error handling with configurable error behavior
20- Tracks success, error, and settle counts separately
21- Has state tracking for when batches are executing
22- Returns the result of the batch function execution
23
24Features:
25- Configurable batch size and wait time
26- Custom batch processing logic via getShouldExecute
27- Event callbacks for monitoring batch operations
28- Error handling for failed batch operations
29- Automatic or manual batch processing
30
31The batcher collects items and processes them in batches based on:
32- Maximum batch size (number of items per batch)
33- Time-based batching (process after X milliseconds)
34- Custom batch processing logic via getShouldExecute
35
36Error Handling:
37- If an `onError` handler is provided, it will be called with the error and batcher instance
38- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
39- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
40- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
41- The error state can be checked using the underlying AsyncBatcher instance
42
43## State Management and Selector
44
45The hook uses TanStack Store for reactive state management. You can subscribe to state changes
46in two ways:
47
48**1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
49
50Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
51needing to pass a selector to the hook. This is ideal when you want to subscribe to state
52in child components.
53
54**2. Using the `selector` parameter (For hook-level subscriptions)**
55
56The `selector` parameter allows you to specify which state changes will trigger a re-render
57at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
58state changes occur.
59
60**By default, there will be no reactive state subscriptions** and you must opt-in to state
61tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
62re-renders and gives you full control over when your component updates.
63
64Available state properties:
65- `errorCount`: Number of batch executions that have resulted in errors
66- `failedItems`: Array of items that failed during batch processing
67- `isEmpty`: Whether the batcher has no items to process
68- `isExecuting`: Whether a batch is currently being processed asynchronously
69- `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing
70- `items`: Array of items currently queued for batch processing
71- `lastResult`: The result from the most recent batch execution
72- `settleCount`: Number of batch executions that have completed (success or error)
73- `size`: Number of items currently in the batch queue
74- `status`: Current processing status ('idle' | 'pending' | 'executing' | 'populated')
75- `successCount`: Number of batch executions that have completed successfully
76- `totalItemsProcessed`: Total number of items processed across all batches
77- `totalItemsFailed`: Total number of items that have failed processing
78
79## Unmount behavior
80
81By default, the hook cancels any pending batch and aborts any in-flight execution when the component unmounts.
82Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
83Use the `onUnmount` option to customize this. For example, to flush pending work instead:
84
85```tsx
86const batcher = useAsyncBatcher(fn, {
87 maxSize: 10,
88 wait: 2000,
89 onUnmount: (b) => b.flush()
90});
91```
92
93Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
94If your batch function updates Preact state, those updates may run after the component has
95unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
96accordingly when using onUnmount with flush.
97
98## Type Parameters
99
100### TValue
101
102`TValue`
103
104### TSelected
105
106`TSelected` = \{
107\}
108
109## Parameters
110
111### fn
112
113(`items`) => `Promise`\<`any`\>
114
115### options?
116
117[`PreactAsyncBatcherOptions`](../interfaces/PreactAsyncBatcherOptions.md)\<`TValue`, `TSelected`\> = `{}`
118
119### selector?
120
121(`state`) => `TSelected`
122
123## Returns
124
125[`PreactAsyncBatcher`](../interfaces/PreactAsyncBatcher.md)\<`TValue`, `TSelected`\>
126
127## Example
128
129```tsx
130// Basic async batcher for API requests - no reactive state subscriptions
131const 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)
147const 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)
161const 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)
175const 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
193const 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
211asyncBatcher.addItem(newItem);
212
213// Manually execute batch
214const result = await asyncBatcher.execute();
215
216// Access the selected state (will be empty object {} unless selector provided)
217const { isExecuting, lastResult, size } = asyncBatcher.state;
218```