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