@tanstack/preact-pacer 0.18.0 → 0.19.1

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 (103) hide show
  1. package/dist/async-batcher/index.cjs +3 -3
  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/useAsyncBatcher.cjs +35 -11
  5. package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -1
  6. package/dist/async-batcher/useAsyncBatcher.d.cts +45 -10
  7. package/dist/async-batcher/useAsyncBatcher.d.ts +45 -10
  8. package/dist/async-batcher/useAsyncBatcher.js +32 -8
  9. package/dist/async-batcher/useAsyncBatcher.js.map +1 -1
  10. package/dist/async-debouncer/index.cjs +3 -3
  11. package/dist/async-debouncer/index.d.cts +2 -2
  12. package/dist/async-debouncer/index.d.ts +2 -2
  13. package/dist/async-debouncer/useAsyncDebouncer.cjs +35 -11
  14. package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -1
  15. package/dist/async-debouncer/useAsyncDebouncer.d.cts +45 -10
  16. package/dist/async-debouncer/useAsyncDebouncer.d.ts +45 -10
  17. package/dist/async-debouncer/useAsyncDebouncer.js +32 -8
  18. package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -1
  19. package/dist/async-queuer/index.cjs +3 -3
  20. package/dist/async-queuer/index.d.cts +2 -2
  21. package/dist/async-queuer/index.d.ts +2 -2
  22. package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -1
  23. package/dist/async-queuer/useAsyncQueuedState.d.cts +2 -2
  24. package/dist/async-queuer/useAsyncQueuedState.d.ts +2 -2
  25. package/dist/async-queuer/useAsyncQueuedState.js.map +1 -1
  26. package/dist/async-queuer/useAsyncQueuer.cjs +35 -11
  27. package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -1
  28. package/dist/async-queuer/useAsyncQueuer.d.cts +45 -10
  29. package/dist/async-queuer/useAsyncQueuer.d.ts +45 -10
  30. package/dist/async-queuer/useAsyncQueuer.js +32 -8
  31. package/dist/async-queuer/useAsyncQueuer.js.map +1 -1
  32. package/dist/async-rate-limiter/index.cjs +3 -3
  33. package/dist/async-rate-limiter/index.d.cts +2 -2
  34. package/dist/async-rate-limiter/index.d.ts +2 -2
  35. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +35 -11
  36. package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -1
  37. package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +45 -10
  38. package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +45 -10
  39. package/dist/async-rate-limiter/useAsyncRateLimiter.js +32 -8
  40. package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -1
  41. package/dist/async-retryer/index.cjs +3 -3
  42. package/dist/async-throttler/index.cjs +3 -3
  43. package/dist/async-throttler/index.d.cts +2 -2
  44. package/dist/async-throttler/index.d.ts +2 -2
  45. package/dist/async-throttler/useAsyncThrottler.cjs +35 -11
  46. package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -1
  47. package/dist/async-throttler/useAsyncThrottler.d.cts +45 -10
  48. package/dist/async-throttler/useAsyncThrottler.d.ts +45 -10
  49. package/dist/async-throttler/useAsyncThrottler.js +32 -8
  50. package/dist/async-throttler/useAsyncThrottler.js.map +1 -1
  51. package/dist/batcher/index.cjs +3 -3
  52. package/dist/batcher/useBatcher.cjs +35 -11
  53. package/dist/batcher/useBatcher.cjs.map +1 -1
  54. package/dist/batcher/useBatcher.d.cts +42 -7
  55. package/dist/batcher/useBatcher.d.ts +42 -7
  56. package/dist/batcher/useBatcher.js +32 -8
  57. package/dist/batcher/useBatcher.js.map +1 -1
  58. package/dist/debouncer/index.cjs +3 -3
  59. package/dist/debouncer/useDebouncer.cjs +35 -11
  60. package/dist/debouncer/useDebouncer.cjs.map +1 -1
  61. package/dist/debouncer/useDebouncer.d.cts +42 -7
  62. package/dist/debouncer/useDebouncer.d.ts +42 -7
  63. package/dist/debouncer/useDebouncer.js +32 -8
  64. package/dist/debouncer/useDebouncer.js.map +1 -1
  65. package/dist/index.cjs +3 -3
  66. package/dist/index.d.cts +6 -6
  67. package/dist/index.d.ts +6 -6
  68. package/dist/provider/PacerProvider.d.cts +1 -1
  69. package/dist/queuer/index.cjs +3 -3
  70. package/dist/queuer/useQueuer.cjs +35 -11
  71. package/dist/queuer/useQueuer.cjs.map +1 -1
  72. package/dist/queuer/useQueuer.d.cts +42 -7
  73. package/dist/queuer/useQueuer.d.ts +42 -7
  74. package/dist/queuer/useQueuer.js +32 -8
  75. package/dist/queuer/useQueuer.js.map +1 -1
  76. package/dist/rate-limiter/index.cjs +3 -3
  77. package/dist/rate-limiter/useRateLimiter.cjs +35 -11
  78. package/dist/rate-limiter/useRateLimiter.cjs.map +1 -1
  79. package/dist/rate-limiter/useRateLimiter.d.cts +42 -7
  80. package/dist/rate-limiter/useRateLimiter.d.ts +42 -7
  81. package/dist/rate-limiter/useRateLimiter.js +32 -8
  82. package/dist/rate-limiter/useRateLimiter.js.map +1 -1
  83. package/dist/throttler/index.cjs +3 -3
  84. package/dist/throttler/useThrottler.cjs +35 -11
  85. package/dist/throttler/useThrottler.cjs.map +1 -1
  86. package/dist/throttler/useThrottler.d.cts +42 -7
  87. package/dist/throttler/useThrottler.d.ts +42 -7
  88. package/dist/throttler/useThrottler.js +32 -8
  89. package/dist/throttler/useThrottler.js.map +1 -1
  90. package/dist/types/index.cjs +3 -3
  91. package/dist/utils/index.cjs +3 -3
  92. package/package.json +3 -3
  93. package/src/async-batcher/useAsyncBatcher.ts +64 -13
  94. package/src/async-debouncer/useAsyncDebouncer.ts +64 -13
  95. package/src/async-queuer/useAsyncQueuedState.ts +2 -2
  96. package/src/async-queuer/useAsyncQueuer.ts +64 -13
  97. package/src/async-rate-limiter/useAsyncRateLimiter.ts +64 -13
  98. package/src/async-throttler/useAsyncThrottler.ts +64 -13
  99. package/src/batcher/useBatcher.ts +61 -8
  100. package/src/debouncer/useDebouncer.ts +61 -8
  101. package/src/queuer/useQueuer.ts +61 -8
  102. package/src/rate-limiter/useRateLimiter.ts +61 -8
  103. package/src/throttler/useThrottler.ts +61 -8
@@ -34,14 +34,24 @@ import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
34
34
  *
35
35
  * ## State Management and Selector
36
36
  *
37
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
38
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
39
- * unnecessary re-renders when irrelevant state changes occur.
37
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
38
+ * in two ways:
39
+ *
40
+ * **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
41
+ *
42
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
43
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
44
+ * in child components.
45
+ *
46
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
47
+ *
48
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
49
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
50
+ * state changes occur.
40
51
  *
41
52
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
42
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
43
- * full control over when your component updates. Only when you provide a selector will the
44
- * component re-render when the selected state values change.
53
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
54
+ * re-renders and gives you full control over when your component updates.
45
55
  *
46
56
  * Available state properties:
47
57
  * - `errorCount`: Number of function executions that have resulted in errors
@@ -63,7 +73,14 @@ import { AsyncRateLimiter } from "@tanstack/pacer/async-rate-limiter";
63
73
  * { limit: 5, window: 1000 } // 5 calls per second
64
74
  * );
65
75
  *
66
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
76
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
77
+ * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
78
+ * {({ rejectionCount }) => (
79
+ * <div>Rejections: {rejectionCount}</div>
80
+ * )}
81
+ * </asyncRateLimiter.Subscribe>
82
+ *
83
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
67
84
  * const asyncRateLimiter = useAsyncRateLimiter(
68
85
  * async (id: string) => {
69
86
  * const data = await api.fetchData(id);
@@ -158,7 +175,14 @@ function useAsyncRateLimiter(fn, options, selector = () => ({})) {
158
175
  ...useDefaultPacerOptions().asyncRateLimiter,
159
176
  ...options
160
177
  };
161
- const [asyncRateLimiter] = useState(() => new AsyncRateLimiter(fn, mergedOptions));
178
+ const [asyncRateLimiter] = useState(() => {
179
+ const rateLimiterInstance = new AsyncRateLimiter(fn, mergedOptions);
180
+ rateLimiterInstance.Subscribe = function Subscribe(props) {
181
+ const selected = useStore(rateLimiterInstance.store, props.selector);
182
+ return typeof props.children === "function" ? props.children(selected) : props.children;
183
+ };
184
+ return rateLimiterInstance;
185
+ });
162
186
  asyncRateLimiter.fn = fn;
163
187
  asyncRateLimiter.setOptions(mergedOptions);
164
188
  const state = useStore(asyncRateLimiter.store, selector);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\n\nexport interface ReactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.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<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant 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. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Opt-in to re-render when execution state changes (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as AsyncRateLimiterOptions<TFn>\n\n const [asyncRateLimiter] = useState(\n () => new AsyncRateLimiter<TFn>(fn, mergedOptions),\n )\n\n asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as ReactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkLA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACkC;CACvC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,oBAAoB,eACnB,IAAI,iBAAsB,IAAI,cAAc,CACnD;AAED,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;CAE1C,MAAM,QAAQ,SAAS,iBAAiB,OAAO,SAAS;AAExD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
1
+ {"version":3,"file":"useAsyncRateLimiter.js","names":[],"sources":["../../src/async-rate-limiter/useAsyncRateLimiter.ts"],"sourcesContent":["import { useMemo, useState } from 'preact/hooks'\nimport { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncRateLimiterOptions,\n AsyncRateLimiterState,\n} from '@tanstack/pacer/async-rate-limiter'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncRateLimiter<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async rate limiter state.\n *\n * This is useful for opting into state re-renders for specific parts of the rate limiter state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </rateLimiter.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the rate limiter state changes\n *\n * Use this instead of `rateLimiter.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `rateLimiter.state` instead of `rateLimiter.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<AsyncRateLimiterState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Rate limiting allows an async function to execute up to a specified limit within a time window,\n * then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,\n * managing resource constraints, or controlling bursts of async operations.\n *\n * Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the rate-limited function.\n *\n * The rate limiter supports two types of windows:\n * - 'fixed': A strict window that resets after the window period. All executions within the window count\n * towards the limit, and the window resets completely after the period.\n * - 'sliding': A rolling window that allows executions as old ones expire. This provides a more\n * consistent rate of execution over time.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and rate limiter 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 AsyncRateLimiter instance\n * - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler\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 `rateLimiter.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 function executions that have resulted in errors\n * - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations\n * - `isExecuting`: Whether the rate-limited function is currently executing asynchronously\n * - `lastResult`: The result from the most recent successful function execution\n * - `rejectionCount`: Number of function executions that have been rejected due to rate limiting\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { limit: 5, window: 1000 } // 5 calls per second\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>\n * {({ rejectionCount }) => (\n * <div>Rejections: {rejectionCount}</div>\n * )}\n * </asyncRateLimiter.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to re-render when results are available (optimized for data display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount\n * })\n * );\n *\n * // Opt-in to re-render when error/rejection state changes (optimized for error handling)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * limit: 5,\n * window: 1000,\n * onError: (error) => console.error('API call failed:', error),\n * onReject: (rateLimiter) => console.log('Rate limit exceeded')\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution metrics change (optimized for stats display)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({\n * successCount: state.successCount,\n * errorCount: state.errorCount,\n * settleCount: state.settleCount,\n * rejectionCount: state.rejectionCount\n * })\n * );\n *\n * // Opt-in to re-render when execution times change (optimized for window calculations)\n * const asyncRateLimiter = useAsyncRateLimiter(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { limit: 5, window: 1000 },\n * (state) => ({ executionTimes: state.executionTimes })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncRateLimiter(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * limit: 10,\n * window: 60000, // 10 calls per minute\n * onReject: (rateLimiter) => {\n * console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);\n * },\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult, rejectionCount } = state;\n * ```\n */\nexport function useAsyncRateLimiter<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncRateLimiterOptions<TFn>,\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncRateLimiter<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncRateLimiter,\n ...options,\n } as AsyncRateLimiterOptions<TFn>\n\n const [asyncRateLimiter] = useState(() => {\n const rateLimiterInstance = new AsyncRateLimiter<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncRateLimiter<TFn, TSelected>\n\n rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncRateLimiterState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(rateLimiterInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return rateLimiterInstance\n })\n\n asyncRateLimiter.fn = fn\n asyncRateLimiter.setOptions(mergedOptions)\n\n const state = useStore(asyncRateLimiter.store, selector)\n\n return useMemo(\n () =>\n ({\n ...asyncRateLimiter,\n state,\n }) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncRateLimiter, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNA,SAAgB,oBAId,IACA,SACA,kBACG,EAAE,GACmC;CACxC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,oBAAoB,eAAe;EACxC,MAAM,sBAAsB,IAAI,iBAC9B,IACA,cACD;AAED,sBAAoB,YAAY,SAAS,UAAqB,OAG3D;GACD,MAAM,WAAW,SAAS,oBAAoB,OAAO,MAAM,SAAS;AAEpE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,kBAAiB,KAAK;AACtB,kBAAiB,WAAW,cAAc;CAE1C,MAAM,QAAQ,SAAS,iBAAiB,OAAO,SAAS;AAExD,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,kBAAkB,MAAM,CAC1B"}
@@ -1,9 +1,9 @@
1
1
 
2
2
 
3
- var __tanstack_pacer_async_retryer = require("@tanstack/pacer/async-retryer");
4
- Object.keys(__tanstack_pacer_async_retryer).forEach(function (k) {
3
+ var _tanstack_pacer_async_retryer = require("@tanstack/pacer/async-retryer");
4
+ Object.keys(_tanstack_pacer_async_retryer).forEach(function (k) {
5
5
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
6
6
  enumerable: true,
7
- get: function () { return __tanstack_pacer_async_retryer[k]; }
7
+ get: function () { return _tanstack_pacer_async_retryer[k]; }
8
8
  });
9
9
  });
@@ -3,10 +3,10 @@ const require_useAsyncThrottledCallback = require('./useAsyncThrottledCallback.c
3
3
 
4
4
  exports.useAsyncThrottledCallback = require_useAsyncThrottledCallback.useAsyncThrottledCallback;
5
5
  exports.useAsyncThrottler = require_useAsyncThrottler.useAsyncThrottler;
6
- var __tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler");
7
- Object.keys(__tanstack_pacer_async_throttler).forEach(function (k) {
6
+ var _tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler");
7
+ Object.keys(_tanstack_pacer_async_throttler).forEach(function (k) {
8
8
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
9
  enumerable: true,
10
- get: function () { return __tanstack_pacer_async_throttler[k]; }
10
+ get: function () { return _tanstack_pacer_async_throttler[k]; }
11
11
  });
12
12
  });
@@ -1,4 +1,4 @@
1
- import { ReactAsyncThrottler, useAsyncThrottler } from "./useAsyncThrottler.cjs";
1
+ import { PreactAsyncThrottler, useAsyncThrottler } from "./useAsyncThrottler.cjs";
2
2
  import { useAsyncThrottledCallback } from "./useAsyncThrottledCallback.cjs";
3
3
  export * from "@tanstack/pacer/async-throttler";
4
- export { ReactAsyncThrottler, useAsyncThrottledCallback, useAsyncThrottler };
4
+ export { PreactAsyncThrottler, useAsyncThrottledCallback, useAsyncThrottler };
@@ -1,4 +1,4 @@
1
- import { ReactAsyncThrottler, useAsyncThrottler } from "./useAsyncThrottler.js";
1
+ import { PreactAsyncThrottler, useAsyncThrottler } from "./useAsyncThrottler.js";
2
2
  import { useAsyncThrottledCallback } from "./useAsyncThrottledCallback.js";
3
3
  export * from "@tanstack/pacer/async-throttler";
4
- export { ReactAsyncThrottler, useAsyncThrottledCallback, useAsyncThrottler };
4
+ export { PreactAsyncThrottler, useAsyncThrottledCallback, useAsyncThrottler };
@@ -1,7 +1,7 @@
1
1
  const require_PacerProvider = require('../provider/PacerProvider.cjs');
2
2
  let preact_hooks = require("preact/hooks");
3
- let __tanstack_preact_store = require("@tanstack/preact-store");
4
- let __tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler");
3
+ let _tanstack_preact_store = require("@tanstack/preact-store");
4
+ let _tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler");
5
5
 
6
6
  //#region src/async-throttler/useAsyncThrottler.ts
7
7
  /**
@@ -27,14 +27,24 @@ let __tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler"
27
27
  *
28
28
  * ## State Management and Selector
29
29
  *
30
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
31
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
32
- * unnecessary re-renders when irrelevant state changes occur.
30
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
31
+ * in two ways:
32
+ *
33
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
34
+ *
35
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
36
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
37
+ * in child components.
38
+ *
39
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
40
+ *
41
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
42
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
43
+ * state changes occur.
33
44
  *
34
45
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
35
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
36
- * full control over when your component updates. Only when you provide a selector will the
37
- * component re-render when the selected state values change.
46
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
47
+ * re-renders and gives you full control over when your component updates.
38
48
  *
39
49
  * Available state properties:
40
50
  * - `errorCount`: Number of function executions that have resulted in errors
@@ -59,7 +69,14 @@ let __tanstack_pacer_async_throttler = require("@tanstack/pacer/async-throttler"
59
69
  * { wait: 1000 }
60
70
  * );
61
71
  *
62
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
72
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
73
+ * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
74
+ * {({ isPending }) => (
75
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
76
+ * )}
77
+ * </asyncThrottler.Subscribe>
78
+ *
79
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
63
80
  * const asyncThrottler = useAsyncThrottler(
64
81
  * async (id: string) => {
65
82
  * const data = await api.fetchData(id);
@@ -140,10 +157,17 @@ function useAsyncThrottler(fn, options, selector = () => ({})) {
140
157
  ...require_PacerProvider.useDefaultPacerOptions().asyncThrottler,
141
158
  ...options
142
159
  };
143
- const [asyncThrottler] = (0, preact_hooks.useState)(() => new __tanstack_pacer_async_throttler.AsyncThrottler(fn, mergedOptions));
160
+ const [asyncThrottler] = (0, preact_hooks.useState)(() => {
161
+ const throttlerInstance = new _tanstack_pacer_async_throttler.AsyncThrottler(fn, mergedOptions);
162
+ throttlerInstance.Subscribe = function Subscribe(props) {
163
+ const selected = (0, _tanstack_preact_store.useStore)(throttlerInstance.store, props.selector);
164
+ return typeof props.children === "function" ? props.children(selected) : props.children;
165
+ };
166
+ return throttlerInstance;
167
+ });
144
168
  asyncThrottler.fn = fn;
145
169
  asyncThrottler.setOptions(mergedOptions);
146
- const state = (0, __tanstack_preact_store.useStore)(asyncThrottler.store, selector);
170
+ const state = (0, _tanstack_preact_store.useStore)(asyncThrottler.store, selector);
147
171
  (0, preact_hooks.useEffect)(() => {
148
172
  return () => asyncThrottler.cancel();
149
173
  }, [asyncThrottler]);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler"],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface ReactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant 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. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to re-render when execution state changes (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const [asyncThrottler] = useState(\n () => new AsyncThrottler<TFn>(fn, mergedOptions),\n )\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n useEffect(() => {\n return () => asyncThrottler.cancel()\n }, [asyncThrottler])\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as ReactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgKA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,mDACC,IAAIC,gDAAoB,IAAI,cAAc,CACjD;AAED,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,8CAAiB,eAAe,OAAO,SAAS;AAEtD,mCAAgB;AACd,eAAa,eAAe,QAAQ;IACnC,CAAC,eAAe,CAAC;AAEpB,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
1
+ {"version":3,"file":"useAsyncThrottler.cjs","names":["useDefaultPacerOptions","AsyncThrottler"],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler 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 `throttler.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 function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n useEffect(() => {\n return () => asyncThrottler.cancel()\n }, [asyncThrottler])\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmMA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,mDAAiC;EACtC,MAAM,oBAAoB,IAAIC,+CAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,gDAAoB,kBAAkB,OAAO,MAAM,SAAS;AAElE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,6CAAiB,eAAe,OAAO,SAAS;AAEtD,mCAAgB;AACd,eAAa,eAAe,QAAQ;IACnC,CAAC,eAAe,CAAC;AAEpB,yCAEK;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
@@ -1,9 +1,27 @@
1
1
  import { Store } from "@tanstack/preact-store";
2
+ import { ComponentChildren } from "preact";
2
3
  import { AnyAsyncFunction } from "@tanstack/pacer/types";
3
4
  import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler";
4
5
 
5
6
  //#region src/async-throttler/useAsyncThrottler.d.ts
6
- interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
7
+ interface PreactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
8
+ /**
9
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.
10
+ *
11
+ * This is useful for opting into state re-renders for specific parts of the throttler state
12
+ * deep in your component tree without needing to pass a selector to the hook.
13
+ *
14
+ * @example
15
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
16
+ * {({ isPending }) => (
17
+ * <div>{isPending ? 'Loading...' : 'Ready'}</div>
18
+ * )}
19
+ * </throttler.Subscribe>
20
+ */
21
+ Subscribe: <TSelected>(props: {
22
+ selector: (state: AsyncThrottlerState<TFn>) => TSelected;
23
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
24
+ }) => ComponentChildren;
7
25
  /**
8
26
  * Reactive state that will be updated and re-rendered when the throttler state changes
9
27
  *
@@ -40,14 +58,24 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
40
58
  *
41
59
  * ## State Management and Selector
42
60
  *
43
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
44
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
45
- * unnecessary re-renders when irrelevant state changes occur.
61
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
62
+ * in two ways:
63
+ *
64
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
65
+ *
66
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
67
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
68
+ * in child components.
69
+ *
70
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
71
+ *
72
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
73
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
74
+ * state changes occur.
46
75
  *
47
76
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
48
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
49
- * full control over when your component updates. Only when you provide a selector will the
50
- * component re-render when the selected state values change.
77
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
78
+ * re-renders and gives you full control over when your component updates.
51
79
  *
52
80
  * Available state properties:
53
81
  * - `errorCount`: Number of function executions that have resulted in errors
@@ -72,7 +100,14 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
72
100
  * { wait: 1000 }
73
101
  * );
74
102
  *
75
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
103
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
104
+ * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
105
+ * {({ isPending }) => (
106
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
107
+ * )}
108
+ * </asyncThrottler.Subscribe>
109
+ *
110
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
76
111
  * const asyncThrottler = useAsyncThrottler(
77
112
  * async (id: string) => {
78
113
  * const data = await api.fetchData(id);
@@ -148,7 +183,7 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
148
183
  * const { isExecuting, lastResult } = state;
149
184
  * ```
150
185
  */
151
- declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): ReactAsyncThrottler<TFn, TSelected>;
186
+ declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): PreactAsyncThrottler<TFn, TSelected>;
152
187
  //#endregion
153
- export { ReactAsyncThrottler, useAsyncThrottler };
188
+ export { PreactAsyncThrottler, useAsyncThrottler };
154
189
  //# sourceMappingURL=useAsyncThrottler.d.cts.map
@@ -1,9 +1,27 @@
1
+ import { ComponentChildren } from "preact";
1
2
  import { Store } from "@tanstack/preact-store";
2
3
  import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler";
3
4
  import { AnyAsyncFunction } from "@tanstack/pacer/types";
4
5
 
5
6
  //#region src/async-throttler/useAsyncThrottler.d.ts
6
- interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
7
+ interface PreactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncThrottler<TFn>, 'store'> {
8
+ /**
9
+ * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.
10
+ *
11
+ * This is useful for opting into state re-renders for specific parts of the throttler state
12
+ * deep in your component tree without needing to pass a selector to the hook.
13
+ *
14
+ * @example
15
+ * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
16
+ * {({ isPending }) => (
17
+ * <div>{isPending ? 'Loading...' : 'Ready'}</div>
18
+ * )}
19
+ * </throttler.Subscribe>
20
+ */
21
+ Subscribe: <TSelected>(props: {
22
+ selector: (state: AsyncThrottlerState<TFn>) => TSelected;
23
+ children: ((state: TSelected) => ComponentChildren) | ComponentChildren;
24
+ }) => ComponentChildren;
7
25
  /**
8
26
  * Reactive state that will be updated and re-rendered when the throttler state changes
9
27
  *
@@ -40,14 +58,24 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
40
58
  *
41
59
  * ## State Management and Selector
42
60
  *
43
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
44
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
45
- * unnecessary re-renders when irrelevant state changes occur.
61
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
62
+ * in two ways:
63
+ *
64
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
65
+ *
66
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
67
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
68
+ * in child components.
69
+ *
70
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
71
+ *
72
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
73
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
74
+ * state changes occur.
46
75
  *
47
76
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
48
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
49
- * full control over when your component updates. Only when you provide a selector will the
50
- * component re-render when the selected state values change.
77
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
78
+ * re-renders and gives you full control over when your component updates.
51
79
  *
52
80
  * Available state properties:
53
81
  * - `errorCount`: Number of function executions that have resulted in errors
@@ -72,7 +100,14 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
72
100
  * { wait: 1000 }
73
101
  * );
74
102
  *
75
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
103
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
104
+ * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
105
+ * {({ isPending }) => (
106
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
107
+ * )}
108
+ * </asyncThrottler.Subscribe>
109
+ *
110
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
76
111
  * const asyncThrottler = useAsyncThrottler(
77
112
  * async (id: string) => {
78
113
  * const data = await api.fetchData(id);
@@ -148,7 +183,7 @@ interface ReactAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}> exte
148
183
  * const { isExecuting, lastResult } = state;
149
184
  * ```
150
185
  */
151
- declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): ReactAsyncThrottler<TFn, TSelected>;
186
+ declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): PreactAsyncThrottler<TFn, TSelected>;
152
187
  //#endregion
153
- export { ReactAsyncThrottler, useAsyncThrottler };
188
+ export { PreactAsyncThrottler, useAsyncThrottler };
154
189
  //# sourceMappingURL=useAsyncThrottler.d.ts.map
@@ -27,14 +27,24 @@ import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
27
27
  *
28
28
  * ## State Management and Selector
29
29
  *
30
- * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you
31
- * to specify which state changes will trigger a re-render, optimizing performance by preventing
32
- * unnecessary re-renders when irrelevant state changes occur.
30
+ * The hook uses TanStack Store for reactive state management. You can subscribe to state changes
31
+ * in two ways:
32
+ *
33
+ * **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
34
+ *
35
+ * Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
36
+ * needing to pass a selector to the hook. This is ideal when you want to subscribe to state
37
+ * in child components.
38
+ *
39
+ * **2. Using the `selector` parameter (For hook-level subscriptions)**
40
+ *
41
+ * The `selector` parameter allows you to specify which state changes will trigger a re-render
42
+ * at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
43
+ * state changes occur.
33
44
  *
34
45
  * **By default, there will be no reactive state subscriptions** and you must opt-in to state
35
- * tracking by providing a selector function. This prevents unnecessary re-renders and gives you
36
- * full control over when your component updates. Only when you provide a selector will the
37
- * component re-render when the selected state values change.
46
+ * tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
47
+ * re-renders and gives you full control over when your component updates.
38
48
  *
39
49
  * Available state properties:
40
50
  * - `errorCount`: Number of function executions that have resulted in errors
@@ -59,7 +69,14 @@ import { AsyncThrottler } from "@tanstack/pacer/async-throttler";
59
69
  * { wait: 1000 }
60
70
  * );
61
71
  *
62
- * // Opt-in to re-render when execution state changes (optimized for loading indicators)
72
+ * // Subscribe to state changes deep in component tree using Subscribe HOC
73
+ * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
74
+ * {({ isPending }) => (
75
+ * <div>{isPending ? 'Processing...' : 'Ready'}</div>
76
+ * )}
77
+ * </asyncThrottler.Subscribe>
78
+ *
79
+ * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
63
80
  * const asyncThrottler = useAsyncThrottler(
64
81
  * async (id: string) => {
65
82
  * const data = await api.fetchData(id);
@@ -140,7 +157,14 @@ function useAsyncThrottler(fn, options, selector = () => ({})) {
140
157
  ...useDefaultPacerOptions().asyncThrottler,
141
158
  ...options
142
159
  };
143
- const [asyncThrottler] = useState(() => new AsyncThrottler(fn, mergedOptions));
160
+ const [asyncThrottler] = useState(() => {
161
+ const throttlerInstance = new AsyncThrottler(fn, mergedOptions);
162
+ throttlerInstance.Subscribe = function Subscribe(props) {
163
+ const selected = useStore(throttlerInstance.store, props.selector);
164
+ return typeof props.children === "function" ? props.children(selected) : props.children;
165
+ };
166
+ return throttlerInstance;
167
+ });
144
168
  asyncThrottler.fn = fn;
145
169
  asyncThrottler.setOptions(mergedOptions);
146
170
  const state = useStore(asyncThrottler.store, selector);
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\n\nexport interface ReactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. The `selector` parameter allows you\n * to specify which state changes will trigger a re-render, optimizing performance by preventing\n * unnecessary re-renders when irrelevant 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. This prevents unnecessary re-renders and gives you\n * full control over when your component updates. Only when you provide a selector will the\n * component re-render when the selected state values change.\n *\n * Available state properties:\n * - `errorCount`: Number of function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Opt-in to re-render when execution state changes (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): ReactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const [asyncThrottler] = useState(\n () => new AsyncThrottler<TFn>(fn, mergedOptions),\n )\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n useEffect(() => {\n return () => asyncThrottler.cancel()\n }, [asyncThrottler])\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as ReactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgKA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,kBAAkB,eACjB,IAAI,eAAoB,IAAI,cAAc,CACjD;AAED,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,iBAAgB;AACd,eAAa,eAAe,QAAQ;IACnC,CAAC,eAAe,CAAC;AAEpB,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
1
+ {"version":3,"file":"useAsyncThrottler.js","names":[],"sources":["../../src/async-throttler/useAsyncThrottler.ts"],"sourcesContent":["import { useEffect, useMemo, useState } from 'preact/hooks'\nimport { AsyncThrottler } from '@tanstack/pacer/async-throttler'\nimport { useStore } from '@tanstack/preact-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/preact-store'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\nimport type {\n AsyncThrottlerOptions,\n AsyncThrottlerState,\n} from '@tanstack/pacer/async-throttler'\nimport type { ComponentChildren } from 'preact'\n\nexport interface PreactAsyncThrottler<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncThrottler<TFn>, 'store'> {\n /**\n * A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.\n *\n * This is useful for opting into state re-renders for specific parts of the throttler state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Loading...' : 'Ready'}</div>\n * )}\n * </throttler.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) => ComponentChildren\n /**\n * Reactive state that will be updated and re-rendered when the throttler state changes\n *\n * Use this instead of `throttler.store.state`\n */\n readonly state: Readonly<TSelected>\n /**\n * @deprecated Use `throttler.state` instead of `throttler.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<AsyncThrottlerState<TFn>>>\n}\n\n/**\n * A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that\n * you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).\n *\n * Async throttling ensures an async function executes at most once within a specified time window,\n * regardless of how many times it is called. This is useful for rate-limiting expensive API calls,\n * database operations, or other async tasks.\n *\n * Unlike the non-async Throttler, this async version supports returning values from the throttled function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the throttled function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and throttler 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 AsyncThrottler 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 `throttler.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 function executions that have resulted in errors\n * - `isExecuting`: Whether the throttled function is currently executing asynchronously\n * - `isPending`: Whether the throttler is waiting for the timeout to trigger execution\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastExecutionTime`: Timestamp of the last function execution in milliseconds\n * - `lastResult`: The result from the most recent successful function execution\n * - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds\n * - `settleCount`: Number of function executions that have completed (success or error)\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')\n * - `successCount`: Number of function executions that have completed successfully\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data; // Return value is preserved\n * },\n * { wait: 1000 }\n * );\n *\n * // Subscribe to state changes deep in component tree using Subscribe HOC\n * <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>\n * {({ isPending }) => (\n * <div>{isPending ? 'Processing...' : 'Ready'}</div>\n * )}\n * </asyncThrottler.Subscribe>\n *\n * // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\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 asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastResult: state.lastResult,\n * successCount: state.successCount,\n * settleCount: state.settleCount\n * })\n * );\n *\n * // Opt-in to re-render when error state changes (optimized for error handling)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * {\n * wait: 1000,\n * onError: (error) => console.error('API call failed:', error)\n * },\n * (state) => ({\n * errorCount: state.errorCount,\n * status: state.status\n * })\n * );\n *\n * // Opt-in to re-render when timing information changes (optimized for timing displays)\n * const asyncThrottler = useAsyncThrottler(\n * async (id: string) => {\n * const data = await api.fetchData(id);\n * return data;\n * },\n * { wait: 1000 },\n * (state) => ({\n * lastExecutionTime: state.lastExecutionTime,\n * nextExecutionTime: state.nextExecutionTime\n * })\n * );\n *\n * // With state management and return value\n * const [data, setData] = useState(null);\n * const { maybeExecute, state } = useAsyncThrottler(\n * async (query) => {\n * const result = await searchAPI(query);\n * setData(result);\n * return result; // Return value can be used by the caller\n * },\n * {\n * wait: 2000,\n * leading: true, // Execute immediately on first call\n * trailing: false // Skip trailing edge updates\n * }\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isExecuting, lastResult } = state;\n * ```\n */\nexport function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(\n fn: TFn,\n options: AsyncThrottlerOptions<TFn>,\n selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): PreactAsyncThrottler<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncThrottler,\n ...options,\n } as AsyncThrottlerOptions<TFn>\n\n const [asyncThrottler] = useState(() => {\n const throttlerInstance = new AsyncThrottler<TFn>(\n fn,\n mergedOptions,\n ) as unknown as PreactAsyncThrottler<TFn, TSelected>\n\n throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncThrottlerState<TFn>) => TSelected\n children: ((state: TSelected) => ComponentChildren) | ComponentChildren\n }) {\n const selected = useStore(throttlerInstance.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n return throttlerInstance\n })\n\n asyncThrottler.fn = fn\n asyncThrottler.setOptions(mergedOptions)\n\n const state = useStore(asyncThrottler.store, selector)\n\n useEffect(() => {\n return () => asyncThrottler.cancel()\n }, [asyncThrottler])\n\n return useMemo(\n () =>\n ({\n ...asyncThrottler,\n state,\n }) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`\n [asyncThrottler, state],\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmMA,SAAgB,kBACd,IACA,SACA,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CAED,MAAM,CAAC,kBAAkB,eAAe;EACtC,MAAM,oBAAoB,IAAI,eAC5B,IACA,cACD;AAED,oBAAkB,YAAY,SAAS,UAAqB,OAGzD;GACD,MAAM,WAAW,SAAS,kBAAkB,OAAO,MAAM,SAAS;AAElE,UAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;AAGZ,SAAO;GACP;AAEF,gBAAe,KAAK;AACpB,gBAAe,WAAW,cAAc;CAExC,MAAM,QAAQ,SAAS,eAAe,OAAO,SAAS;AAEtD,iBAAgB;AACd,eAAa,eAAe,QAAQ;IACnC,CAAC,eAAe,CAAC;AAEpB,QAAO,eAEF;EACC,GAAG;EACH;EACD,GACH,CAAC,gBAAgB,MAAM,CACxB"}
@@ -3,10 +3,10 @@ const require_useBatchedCallback = require('./useBatchedCallback.cjs');
3
3
 
4
4
  exports.useBatchedCallback = require_useBatchedCallback.useBatchedCallback;
5
5
  exports.useBatcher = require_useBatcher.useBatcher;
6
- var __tanstack_pacer_batcher = require("@tanstack/pacer/batcher");
7
- Object.keys(__tanstack_pacer_batcher).forEach(function (k) {
6
+ var _tanstack_pacer_batcher = require("@tanstack/pacer/batcher");
7
+ Object.keys(_tanstack_pacer_batcher).forEach(function (k) {
8
8
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
9
9
  enumerable: true,
10
- get: function () { return __tanstack_pacer_batcher[k]; }
10
+ get: function () { return _tanstack_pacer_batcher[k]; }
11
11
  });
12
12
  });