@tanstack/solid-pacer 0.18.4 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/async-batcher/createAsyncBatcher.cjs +32 -2
- package/dist/async-batcher/createAsyncBatcher.cjs.map +1 -1
- package/dist/async-batcher/createAsyncBatcher.d.cts +28 -2
- package/dist/async-batcher/createAsyncBatcher.d.ts +28 -2
- package/dist/async-batcher/createAsyncBatcher.js +32 -2
- package/dist/async-batcher/createAsyncBatcher.js.map +1 -1
- package/dist/async-batcher/index.cjs +1 -0
- package/dist/async-batcher/index.d.cts +2 -2
- package/dist/async-batcher/index.d.ts +2 -2
- package/dist/async-debouncer/createAsyncDebouncer.cjs +26 -3
- package/dist/async-debouncer/createAsyncDebouncer.cjs.map +1 -1
- package/dist/async-debouncer/createAsyncDebouncer.d.cts +27 -2
- package/dist/async-debouncer/createAsyncDebouncer.d.ts +27 -2
- package/dist/async-debouncer/createAsyncDebouncer.js +26 -3
- package/dist/async-debouncer/createAsyncDebouncer.js.map +1 -1
- package/dist/async-debouncer/index.cjs +1 -0
- package/dist/async-debouncer/index.d.cts +2 -2
- package/dist/async-debouncer/index.d.ts +2 -2
- package/dist/async-queuer/createAsyncQueuer.cjs +32 -2
- package/dist/async-queuer/createAsyncQueuer.cjs.map +1 -1
- package/dist/async-queuer/createAsyncQueuer.d.cts +28 -2
- package/dist/async-queuer/createAsyncQueuer.d.ts +28 -2
- package/dist/async-queuer/createAsyncQueuer.js +32 -2
- package/dist/async-queuer/createAsyncQueuer.js.map +1 -1
- package/dist/async-queuer/index.cjs +1 -0
- package/dist/async-queuer/index.d.cts +2 -2
- package/dist/async-queuer/index.d.ts +2 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.cjs +16 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.cjs.map +1 -1
- package/dist/async-rate-limiter/createAsyncRateLimiter.d.cts +15 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.d.ts +15 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.js +16 -2
- package/dist/async-rate-limiter/createAsyncRateLimiter.js.map +1 -1
- package/dist/async-rate-limiter/index.cjs +1 -0
- package/dist/async-rate-limiter/index.d.cts +2 -2
- package/dist/async-rate-limiter/index.d.ts +2 -2
- package/dist/async-throttler/createAsyncThrottler.cjs +31 -2
- package/dist/async-throttler/createAsyncThrottler.cjs.map +1 -1
- package/dist/async-throttler/createAsyncThrottler.d.cts +27 -2
- package/dist/async-throttler/createAsyncThrottler.d.ts +27 -2
- package/dist/async-throttler/createAsyncThrottler.js +31 -2
- package/dist/async-throttler/createAsyncThrottler.js.map +1 -1
- package/dist/async-throttler/index.cjs +1 -0
- package/dist/async-throttler/index.d.cts +2 -2
- package/dist/async-throttler/index.d.ts +2 -2
- package/dist/batcher/createBatcher.cjs +23 -2
- package/dist/batcher/createBatcher.cjs.map +1 -1
- package/dist/batcher/createBatcher.d.cts +22 -2
- package/dist/batcher/createBatcher.d.ts +22 -2
- package/dist/batcher/createBatcher.js +23 -2
- package/dist/batcher/createBatcher.js.map +1 -1
- package/dist/batcher/index.cjs +1 -0
- package/dist/batcher/index.d.cts +2 -2
- package/dist/batcher/index.d.ts +2 -2
- package/dist/debouncer/createDebouncedSignal.cjs.map +1 -1
- package/dist/debouncer/createDebouncedSignal.d.cts +3 -3
- package/dist/debouncer/createDebouncedSignal.d.ts +3 -3
- package/dist/debouncer/createDebouncedSignal.js.map +1 -1
- package/dist/debouncer/createDebouncedValue.cjs.map +1 -1
- package/dist/debouncer/createDebouncedValue.d.cts +3 -3
- package/dist/debouncer/createDebouncedValue.d.ts +3 -3
- package/dist/debouncer/createDebouncedValue.js.map +1 -1
- package/dist/debouncer/createDebouncer.cjs +17 -3
- package/dist/debouncer/createDebouncer.cjs.map +1 -1
- package/dist/debouncer/createDebouncer.d.cts +21 -2
- package/dist/debouncer/createDebouncer.d.ts +21 -2
- package/dist/debouncer/createDebouncer.js +17 -3
- package/dist/debouncer/createDebouncer.js.map +1 -1
- package/dist/debouncer/index.cjs +1 -0
- package/dist/debouncer/index.d.cts +2 -2
- package/dist/debouncer/index.d.ts +2 -2
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +11 -11
- package/dist/index.d.ts +11 -11
- package/dist/provider/index.cjs +1 -0
- package/dist/queuer/createQueuedSignal.cjs.map +1 -1
- package/dist/queuer/createQueuedSignal.d.cts +3 -3
- package/dist/queuer/createQueuedSignal.d.ts +3 -3
- package/dist/queuer/createQueuedSignal.js.map +1 -1
- package/dist/queuer/createQueuer.cjs +23 -2
- package/dist/queuer/createQueuer.cjs.map +1 -1
- package/dist/queuer/createQueuer.d.cts +22 -2
- package/dist/queuer/createQueuer.d.ts +22 -2
- package/dist/queuer/createQueuer.js +23 -2
- package/dist/queuer/createQueuer.js.map +1 -1
- package/dist/queuer/index.cjs +1 -0
- package/dist/queuer/index.d.cts +2 -2
- package/dist/queuer/index.d.ts +2 -2
- package/dist/rate-limiter/createRateLimitedSignal.cjs.map +1 -1
- package/dist/rate-limiter/createRateLimitedSignal.d.cts +3 -3
- package/dist/rate-limiter/createRateLimitedSignal.d.ts +3 -3
- package/dist/rate-limiter/createRateLimitedSignal.js.map +1 -1
- package/dist/rate-limiter/createRateLimitedValue.cjs.map +1 -1
- package/dist/rate-limiter/createRateLimitedValue.d.cts +3 -3
- package/dist/rate-limiter/createRateLimitedValue.d.ts +3 -3
- package/dist/rate-limiter/createRateLimitedValue.js.map +1 -1
- package/dist/rate-limiter/createRateLimiter.cjs +9 -2
- package/dist/rate-limiter/createRateLimiter.cjs.map +1 -1
- package/dist/rate-limiter/createRateLimiter.d.cts +9 -2
- package/dist/rate-limiter/createRateLimiter.d.ts +9 -2
- package/dist/rate-limiter/createRateLimiter.js +9 -2
- package/dist/rate-limiter/createRateLimiter.js.map +1 -1
- package/dist/rate-limiter/index.cjs +1 -0
- package/dist/rate-limiter/index.d.cts +2 -2
- package/dist/rate-limiter/index.d.ts +2 -2
- package/dist/throttler/createThrottledSignal.cjs.map +1 -1
- package/dist/throttler/createThrottledSignal.d.cts +3 -3
- package/dist/throttler/createThrottledSignal.d.ts +3 -3
- package/dist/throttler/createThrottledSignal.js.map +1 -1
- package/dist/throttler/createThrottledValue.cjs.map +1 -1
- package/dist/throttler/createThrottledValue.d.cts +3 -3
- package/dist/throttler/createThrottledValue.d.ts +3 -3
- package/dist/throttler/createThrottledValue.js.map +1 -1
- package/dist/throttler/createThrottler.cjs +17 -3
- package/dist/throttler/createThrottler.cjs.map +1 -1
- package/dist/throttler/createThrottler.d.cts +21 -2
- package/dist/throttler/createThrottler.d.ts +21 -2
- package/dist/throttler/createThrottler.js +17 -3
- package/dist/throttler/createThrottler.js.map +1 -1
- package/dist/throttler/index.cjs +1 -0
- package/dist/throttler/index.d.cts +2 -2
- package/dist/throttler/index.d.ts +2 -2
- package/package.json +32 -31
- package/src/async-batcher/createAsyncBatcher.ts +44 -3
- package/src/async-debouncer/createAsyncDebouncer.ts +37 -4
- package/src/async-queuer/createAsyncQueuer.ts +44 -3
- package/src/async-rate-limiter/createAsyncRateLimiter.ts +30 -3
- package/src/async-throttler/createAsyncThrottler.ts +43 -3
- package/src/batcher/createBatcher.ts +38 -3
- package/src/debouncer/createDebouncedSignal.ts +3 -6
- package/src/debouncer/createDebouncedValue.ts +3 -6
- package/src/debouncer/createDebouncer.ts +30 -4
- package/src/queuer/createQueuedSignal.ts +3 -3
- package/src/queuer/createQueuer.ts +37 -3
- package/src/rate-limiter/createRateLimitedSignal.ts +6 -6
- package/src/rate-limiter/createRateLimitedValue.ts +6 -6
- package/src/rate-limiter/createRateLimiter.ts +22 -3
- package/src/throttler/createThrottledSignal.ts +3 -6
- package/src/throttler/createThrottledValue.ts +3 -6
- package/src/throttler/createThrottler.ts +30 -4
package/README.md
CHANGED
|
@@ -91,7 +91,7 @@ A lightweight timing and scheduling library for debouncing, throttling, rate lim
|
|
|
91
91
|
> - [**React Pacer**](https://tanstack.com/pacer/latest/docs/framework/react/react-pacer)
|
|
92
92
|
> - [**Preact Pacer**](https://tanstack.com/pacer/latest/docs/framework/preact/preact-pacer)
|
|
93
93
|
> - [**Solid Pacer**](https://tanstack.com/pacer/latest/docs/framework/solid/solid-pacer)
|
|
94
|
-
> - Angular Pacer
|
|
94
|
+
> - [**Angular Pacer**](https://tanstack.com/pacer/latest/docs/framework/angular/angular-pacer)
|
|
95
95
|
> - Svelte Pacer - needs a contributor!
|
|
96
96
|
> - Vue Pacer - needs a contributor!
|
|
97
97
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
2
|
+
let solid_js = require("solid-js");
|
|
2
3
|
let _tanstack_pacer_async_batcher = require("@tanstack/pacer/async-batcher");
|
|
3
4
|
let _tanstack_solid_store = require("@tanstack/solid-store");
|
|
4
5
|
|
|
@@ -65,6 +66,25 @@ let _tanstack_solid_store = require("@tanstack/solid-store");
|
|
|
65
66
|
* - `settleCount`: Number of batch executions that have completed (successful or failed)
|
|
66
67
|
* - `successCount`: Number of successful batch executions
|
|
67
68
|
*
|
|
69
|
+
* ## Unmount behavior
|
|
70
|
+
*
|
|
71
|
+
* By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts.
|
|
72
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
73
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
74
|
+
*
|
|
75
|
+
* ```tsx
|
|
76
|
+
* const batcher = createAsyncBatcher(fn, {
|
|
77
|
+
* maxSize: 10,
|
|
78
|
+
* wait: 2000,
|
|
79
|
+
* onUnmount: (b) => b.flush()
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
84
|
+
* If your batch function updates Solid signals, those updates may run after the component has
|
|
85
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
86
|
+
* using onUnmount with flush.
|
|
87
|
+
*
|
|
68
88
|
* Example usage:
|
|
69
89
|
* ```tsx
|
|
70
90
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -116,15 +136,25 @@ let _tanstack_solid_store = require("@tanstack/solid-store");
|
|
|
116
136
|
* ```
|
|
117
137
|
*/
|
|
118
138
|
function createAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
119
|
-
const
|
|
139
|
+
const mergedOptions = {
|
|
120
140
|
...require_PacerProvider.useDefaultPacerOptions().asyncBatcher,
|
|
121
141
|
...options
|
|
122
|
-
}
|
|
142
|
+
};
|
|
143
|
+
const asyncBatcher = new _tanstack_pacer_async_batcher.AsyncBatcher(fn, mergedOptions);
|
|
123
144
|
asyncBatcher.Subscribe = function Subscribe(props) {
|
|
124
145
|
const selected = (0, _tanstack_solid_store.useStore)(asyncBatcher.store, props.selector);
|
|
125
146
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
126
147
|
};
|
|
127
148
|
const state = (0, _tanstack_solid_store.useStore)(asyncBatcher.store, selector);
|
|
149
|
+
(0, solid_js.createEffect)(() => {
|
|
150
|
+
(0, solid_js.onCleanup)(() => {
|
|
151
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
152
|
+
else {
|
|
153
|
+
asyncBatcher.cancel();
|
|
154
|
+
asyncBatcher.abort();
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
});
|
|
128
158
|
return {
|
|
129
159
|
...asyncBatcher,
|
|
130
160
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncBatcher.cjs","names":["AsyncBatcher","useDefaultPacerOptions"],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<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 * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher 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 * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\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 * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ hasError: state.hasError, lastError: state.lastError })\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 { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6JA,SAAgB,mBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACiC;CAMtC,MAAM,eAAe,IAAIA,2CACvB,IANoB;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,+CAAoB,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,aAAa,OAAO,SAAS;AAEpD,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncBatcher.cjs","names":["useDefaultPacerOptions","AsyncBatcher"],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning 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: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<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 * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher 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 * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning 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 = createAsyncBatcher(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 Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\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 * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ hasError: state.hasError, lastError: state.lastError })\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 { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAIC,2CACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,+CAAoB,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,aAAa,OAAO,SAAS;AAEpD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -3,6 +3,13 @@ import { Store } from "@tanstack/solid-store";
|
|
|
3
3
|
import { Accessor, JSX } from "solid-js";
|
|
4
4
|
|
|
5
5
|
//#region src/async-batcher/createAsyncBatcher.d.ts
|
|
6
|
+
interface SolidAsyncBatcherOptions<TValue, TSelected = {}> extends AsyncBatcherOptions<TValue> {
|
|
7
|
+
/**
|
|
8
|
+
* Optional callback invoked when the owning 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: SolidAsyncBatcher<TValue, TSelected>) => void;
|
|
12
|
+
}
|
|
6
13
|
interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
|
|
7
14
|
/**
|
|
8
15
|
* A Solid component that allows you to subscribe to the batcher state.
|
|
@@ -96,6 +103,25 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
96
103
|
* - `settleCount`: Number of batch executions that have completed (successful or failed)
|
|
97
104
|
* - `successCount`: Number of successful batch executions
|
|
98
105
|
*
|
|
106
|
+
* ## Unmount behavior
|
|
107
|
+
*
|
|
108
|
+
* By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts.
|
|
109
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
110
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
111
|
+
*
|
|
112
|
+
* ```tsx
|
|
113
|
+
* const batcher = createAsyncBatcher(fn, {
|
|
114
|
+
* maxSize: 10,
|
|
115
|
+
* wait: 2000,
|
|
116
|
+
* onUnmount: (b) => b.flush()
|
|
117
|
+
* });
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
121
|
+
* If your batch function updates Solid signals, those updates may run after the component has
|
|
122
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
123
|
+
* using onUnmount with flush.
|
|
124
|
+
*
|
|
99
125
|
* Example usage:
|
|
100
126
|
* ```tsx
|
|
101
127
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -146,7 +172,7 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
146
172
|
* const { items, isExecuting } = asyncBatcher.state();
|
|
147
173
|
* ```
|
|
148
174
|
*/
|
|
149
|
-
declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?:
|
|
175
|
+
declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: SolidAsyncBatcherOptions<TValue, TSelected>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>;
|
|
150
176
|
//#endregion
|
|
151
|
-
export { SolidAsyncBatcher, createAsyncBatcher };
|
|
177
|
+
export { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher };
|
|
152
178
|
//# sourceMappingURL=createAsyncBatcher.d.cts.map
|
|
@@ -3,6 +3,13 @@ import { AsyncBatcher, AsyncBatcherOptions, AsyncBatcherState } from "@tanstack/
|
|
|
3
3
|
import { Store } from "@tanstack/solid-store";
|
|
4
4
|
|
|
5
5
|
//#region src/async-batcher/createAsyncBatcher.d.ts
|
|
6
|
+
interface SolidAsyncBatcherOptions<TValue, TSelected = {}> extends AsyncBatcherOptions<TValue> {
|
|
7
|
+
/**
|
|
8
|
+
* Optional callback invoked when the owning 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: SolidAsyncBatcher<TValue, TSelected>) => void;
|
|
12
|
+
}
|
|
6
13
|
interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TValue>, 'store'> {
|
|
7
14
|
/**
|
|
8
15
|
* A Solid component that allows you to subscribe to the batcher state.
|
|
@@ -96,6 +103,25 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
96
103
|
* - `settleCount`: Number of batch executions that have completed (successful or failed)
|
|
97
104
|
* - `successCount`: Number of successful batch executions
|
|
98
105
|
*
|
|
106
|
+
* ## Unmount behavior
|
|
107
|
+
*
|
|
108
|
+
* By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts.
|
|
109
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
110
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
111
|
+
*
|
|
112
|
+
* ```tsx
|
|
113
|
+
* const batcher = createAsyncBatcher(fn, {
|
|
114
|
+
* maxSize: 10,
|
|
115
|
+
* wait: 2000,
|
|
116
|
+
* onUnmount: (b) => b.flush()
|
|
117
|
+
* });
|
|
118
|
+
* ```
|
|
119
|
+
*
|
|
120
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
121
|
+
* If your batch function updates Solid signals, those updates may run after the component has
|
|
122
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
123
|
+
* using onUnmount with flush.
|
|
124
|
+
*
|
|
99
125
|
* Example usage:
|
|
100
126
|
* ```tsx
|
|
101
127
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -146,7 +172,7 @@ interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<AsyncBatcher<TV
|
|
|
146
172
|
* const { items, isExecuting } = asyncBatcher.state();
|
|
147
173
|
* ```
|
|
148
174
|
*/
|
|
149
|
-
declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?:
|
|
175
|
+
declare function createAsyncBatcher<TValue, TSelected = {}>(fn: (items: Array<TValue>) => Promise<any>, options?: SolidAsyncBatcherOptions<TValue, TSelected>, selector?: (state: AsyncBatcherState<TValue>) => TSelected): SolidAsyncBatcher<TValue, TSelected>;
|
|
150
176
|
//#endregion
|
|
151
|
-
export { SolidAsyncBatcher, createAsyncBatcher };
|
|
177
|
+
export { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher };
|
|
152
178
|
//# sourceMappingURL=createAsyncBatcher.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { useDefaultPacerOptions } from "../provider/PacerProvider.js";
|
|
2
|
+
import { createEffect, onCleanup } from "solid-js";
|
|
2
3
|
import { AsyncBatcher } from "@tanstack/pacer/async-batcher";
|
|
3
4
|
import { useStore } from "@tanstack/solid-store";
|
|
4
5
|
|
|
@@ -65,6 +66,25 @@ import { useStore } from "@tanstack/solid-store";
|
|
|
65
66
|
* - `settleCount`: Number of batch executions that have completed (successful or failed)
|
|
66
67
|
* - `successCount`: Number of successful batch executions
|
|
67
68
|
*
|
|
69
|
+
* ## Unmount behavior
|
|
70
|
+
*
|
|
71
|
+
* By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning component unmounts.
|
|
72
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
73
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
74
|
+
*
|
|
75
|
+
* ```tsx
|
|
76
|
+
* const batcher = createAsyncBatcher(fn, {
|
|
77
|
+
* maxSize: 10,
|
|
78
|
+
* wait: 2000,
|
|
79
|
+
* onUnmount: (b) => b.flush()
|
|
80
|
+
* });
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
84
|
+
* If your batch function updates Solid signals, those updates may run after the component has
|
|
85
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
86
|
+
* using onUnmount with flush.
|
|
87
|
+
*
|
|
68
88
|
* Example usage:
|
|
69
89
|
* ```tsx
|
|
70
90
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -116,15 +136,25 @@ import { useStore } from "@tanstack/solid-store";
|
|
|
116
136
|
* ```
|
|
117
137
|
*/
|
|
118
138
|
function createAsyncBatcher(fn, options = {}, selector = () => ({})) {
|
|
119
|
-
const
|
|
139
|
+
const mergedOptions = {
|
|
120
140
|
...useDefaultPacerOptions().asyncBatcher,
|
|
121
141
|
...options
|
|
122
|
-
}
|
|
142
|
+
};
|
|
143
|
+
const asyncBatcher = new AsyncBatcher(fn, mergedOptions);
|
|
123
144
|
asyncBatcher.Subscribe = function Subscribe(props) {
|
|
124
145
|
const selected = useStore(asyncBatcher.store, props.selector);
|
|
125
146
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
126
147
|
};
|
|
127
148
|
const state = useStore(asyncBatcher.store, selector);
|
|
149
|
+
createEffect(() => {
|
|
150
|
+
onCleanup(() => {
|
|
151
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncBatcher);
|
|
152
|
+
else {
|
|
153
|
+
asyncBatcher.cancel();
|
|
154
|
+
asyncBatcher.abort();
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
});
|
|
128
158
|
return {
|
|
129
159
|
...asyncBatcher,
|
|
130
160
|
state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<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 * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher 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 * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\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 * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ hasError: state.hasError, lastError: state.lastError })\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 { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: AsyncBatcherOptions<TValue> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as AsyncBatcherOptions<TValue>\n\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6JA,SAAgB,mBACd,IACA,UAAuC,EAAE,EACzC,kBACG,EAAE,GACiC;CAMtC,MAAM,eAAe,IAAI,aACvB,IANoB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,SAAS,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncBatcher.js","names":[],"sources":["../../src/async-batcher/createAsyncBatcher.ts"],"sourcesContent":["import { AsyncBatcher } from '@tanstack/pacer/async-batcher'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncBatcherOptions,\n AsyncBatcherState,\n} from '@tanstack/pacer/async-batcher'\n\nexport interface SolidAsyncBatcherOptions<\n TValue,\n TSelected = {},\n> extends AsyncBatcherOptions<TValue> {\n /**\n * Optional callback invoked when the owning 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: SolidAsyncBatcher<TValue, TSelected>) => void\n}\n\nexport interface SolidAsyncBatcher<TValue, TSelected = {}> extends Omit<\n AsyncBatcher<TValue>,\n 'store'\n> {\n /**\n * A Solid component that allows you to subscribe to the batcher state.\n *\n * This is useful for tracking 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, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>Batch: {state().size} items, {state().isExecuting ? 'Executing...' : 'Idle'}</div>\n * )}\n * </batcher.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the batcher state changes\n *\n * Use this instead of `batcher.store.state`\n */\n readonly state: Accessor<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 * Creates a Solid-compatible AsyncBatcher instance for managing asynchronous batches of items, exposing Solid signals for all stateful properties.\n *\n * This is the async version of the createBatcher 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 * - All stateful properties (items, counts, etc.) are exposed as Solid signals for reactivity\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` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `errorCount`: Number of failed batch executions\n * - `executionCount`: Total number of batch execution attempts (successful + failed)\n * - `hasError`: Whether the last batch execution resulted in an error\n * - `isExecuting`: Whether a batch execution is currently in progress\n * - `items`: Array of items currently queued for batching\n * - `lastError`: The error from the most recent failed batch execution (if any)\n * - `lastResult`: The result from the most recent successful batch execution\n * - `settleCount`: Number of batch executions that have completed (successful or failed)\n * - `successCount`: Number of successful batch executions\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending batch and aborts any in-flight execution when the owning 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 = createAsyncBatcher(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 Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * Example usage:\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const asyncBatcher = createAsyncBatcher(\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 * // Opt-in to track items or isExecuting changes (optimized for UI updates)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ items: state.items, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const asyncBatcher = createAsyncBatcher(\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) => ({ hasError: state.hasError, lastError: state.lastError })\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 { items, isExecuting } = asyncBatcher.state();\n * ```\n */\nexport function createAsyncBatcher<TValue, TSelected = {}>(\n fn: (items: Array<TValue>) => Promise<any>,\n options: SolidAsyncBatcherOptions<TValue, TSelected> = {},\n selector: (state: AsyncBatcherState<TValue>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncBatcher<TValue, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncBatcher,\n ...options,\n } as SolidAsyncBatcherOptions<TValue, TSelected>\n const asyncBatcher = new AsyncBatcher<TValue>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncBatcher<TValue, TSelected>\n\n asyncBatcher.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncBatcherState<TValue>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncBatcher.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncBatcher.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncBatcher)\n } else {\n asyncBatcher.cancel()\n asyncBatcher.abort()\n }\n })\n })\n\n return {\n ...asyncBatcher,\n state,\n } as SolidAsyncBatcher<TValue, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4LA,SAAgB,mBACd,IACA,UAAuD,EAAE,EACzD,kBACG,EAAE,GACiC;CACtC,MAAM,gBAAgB;EACpB,GAAG,wBAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,eAAe,IAAI,aACvB,IACA,cACD;AAED,cAAa,YAAY,SAAS,UAAqB,OAGpD;EACD,MAAM,WAAW,SAAS,aAAa,OAAO,MAAM,SAAS;AAE7D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,QAAQ,SAAS,aAAa,OAAO,SAAS;AAEpD,oBAAmB;AACjB,kBAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,aAAa;QAChC;AACL,iBAAa,QAAQ;AACrB,iBAAa,OAAO;;IAEtB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { SolidAsyncBatcher, createAsyncBatcher } from "./createAsyncBatcher.cjs";
|
|
1
|
+
import { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher } from "./createAsyncBatcher.cjs";
|
|
2
2
|
export * from "@tanstack/pacer/async-batcher";
|
|
3
|
-
export { SolidAsyncBatcher, createAsyncBatcher };
|
|
3
|
+
export { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { SolidAsyncBatcher, createAsyncBatcher } from "./createAsyncBatcher.js";
|
|
1
|
+
import { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher } from "./createAsyncBatcher.js";
|
|
2
2
|
export * from "@tanstack/pacer/async-batcher";
|
|
3
|
-
export { SolidAsyncBatcher, createAsyncBatcher };
|
|
3
|
+
export { SolidAsyncBatcher, SolidAsyncBatcherOptions, createAsyncBatcher };
|
|
@@ -60,6 +60,24 @@ let _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer")
|
|
|
60
60
|
* - `lastResult`: The result from the most recent successful execution
|
|
61
61
|
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
|
|
62
62
|
*
|
|
63
|
+
* ## Unmount behavior
|
|
64
|
+
*
|
|
65
|
+
* By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning 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 = createAsyncDebouncer(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 Solid signals, those updates may run after the component has
|
|
78
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
79
|
+
* using onUnmount with flush.
|
|
80
|
+
*
|
|
63
81
|
* @example
|
|
64
82
|
* ```tsx
|
|
65
83
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -103,10 +121,11 @@ let _tanstack_pacer_async_debouncer = require("@tanstack/pacer/async-debouncer")
|
|
|
103
121
|
* ```
|
|
104
122
|
*/
|
|
105
123
|
function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
106
|
-
const
|
|
124
|
+
const mergedOptions = {
|
|
107
125
|
...require_PacerProvider.useDefaultPacerOptions().asyncDebouncer,
|
|
108
126
|
...options
|
|
109
|
-
}
|
|
127
|
+
};
|
|
128
|
+
const asyncDebouncer = new _tanstack_pacer_async_debouncer.AsyncDebouncer(fn, mergedOptions);
|
|
110
129
|
asyncDebouncer.Subscribe = function Subscribe(props) {
|
|
111
130
|
const selected = (0, _tanstack_solid_store.useStore)(asyncDebouncer.store, props.selector);
|
|
112
131
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
@@ -114,7 +133,11 @@ function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
114
133
|
const state = (0, _tanstack_solid_store.useStore)(asyncDebouncer.store, selector);
|
|
115
134
|
(0, solid_js.createEffect)(() => {
|
|
116
135
|
(0, solid_js.onCleanup)(() => {
|
|
117
|
-
|
|
136
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
137
|
+
else {
|
|
138
|
+
asyncDebouncer.cancel();
|
|
139
|
+
asyncDebouncer.abort();
|
|
140
|
+
}
|
|
118
141
|
});
|
|
119
142
|
});
|
|
120
143
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createAsyncDebouncer.cjs","names":["AsyncDebouncer","useDefaultPacerOptions"],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: AsyncDebouncerOptions<TFn>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as AsyncDebouncerOptions<TFn>\n\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n asyncDebouncer.cancel()\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CAMrC,MAAM,iBAAiB,IAAIA,+CACzB,IANoB;EACpB,GAAGC,8CAAwB,CAAC;EAC5B,GAAG;EACJ,CAKA;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,+CAAoB,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,eAAe,OAAO,SAAS;AAEtD,kCAAmB;AACjB,gCAAgB;AACd,kBAAe,QAAQ;IACvB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
1
|
+
{"version":3,"file":"createAsyncDebouncer.cjs","names":["useDefaultPacerOptions","AsyncDebouncer"],"sources":["../../src/async-debouncer/createAsyncDebouncer.ts"],"sourcesContent":["import { AsyncDebouncer } from '@tanstack/pacer/async-debouncer'\nimport { useStore } from '@tanstack/solid-store'\nimport { createEffect, onCleanup } from 'solid-js'\nimport { useDefaultPacerOptions } from '../provider/PacerProvider'\nimport type { Store } from '@tanstack/solid-store'\nimport type { Accessor, JSX } from 'solid-js'\nimport type {\n AsyncDebouncerOptions,\n AsyncDebouncerState,\n} from '@tanstack/pacer/async-debouncer'\nimport type { AnyAsyncFunction } from '@tanstack/pacer/types'\n\nexport interface SolidAsyncDebouncerOptions<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends AsyncDebouncerOptions<TFn> {\n /**\n * Optional callback invoked when the owning component unmounts. Receives the debouncer instance.\n * When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.\n */\n onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void\n}\n\nexport interface SolidAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n> extends Omit<AsyncDebouncer<TFn>, 'store'> {\n /**\n * A Solid component that allows you to subscribe to the debouncer state.\n *\n * This is useful for tracking specific parts of the debouncer state\n * deep in your component tree without needing to pass a selector to the hook.\n *\n * @example\n * <debouncer.Subscribe selector={(state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })}>\n * {(state) => (\n * <div>{state().isPending ? 'Waiting...' : state().isExecuting ? 'Executing...' : 'Ready'}</div>\n * )}\n * </debouncer.Subscribe>\n */\n Subscribe: <TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) => JSX.Element\n /**\n * Reactive state that will be updated when the debouncer state changes\n *\n * Use this instead of `debouncer.store.state`\n */\n readonly state: Accessor<Readonly<TSelected>>\n /**\n * @deprecated Use `debouncer.state` instead of `debouncer.store.state` if you want to read reactive state.\n * The state on the store object is not reactive, as it has not been wrapped in a `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<AsyncDebouncerState<TFn>>>\n}\n\n/**\n * A low-level Solid hook that creates an `AsyncDebouncer` instance to delay execution of an async function.\n *\n * This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that\n * you can integrate with any state management solution (createSignal, etc).\n *\n * Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.\n * Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing\n * or input changes where you only want to execute the handler after the events have stopped occurring.\n *\n * Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until\n * the function stops being called for the specified delay period.\n *\n * Unlike the non-async Debouncer, this async version supports returning values from the debounced function,\n * making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call\n * instead of setting the result on a state variable from within the debounced function.\n *\n * Error Handling:\n * - If an `onError` handler is provided, it will be called with the error and debouncer instance\n * - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown\n * - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed\n * - Both onError and throwOnError can be used together - the handler will be called before any error is thrown\n * - The error state can be checked using the underlying AsyncDebouncer instance\n *\n * ## State Management and Selector\n *\n * The hook uses TanStack Store for reactive state management. You can subscribe to state changes\n * in two ways:\n *\n * **1. Using `debouncer.Subscribe` component (Recommended for component tree subscriptions)**\n *\n * Use the `Subscribe` component 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 reactive updates\n * at the hook level, optimizing performance by preventing unnecessary updates 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` component. This prevents unnecessary\n * updates and gives you full control over when your component tracks state changes.\n *\n * Available state properties:\n * - `canLeadingExecute`: Whether the debouncer can execute on the leading edge\n * - `executionCount`: Number of function executions that have been completed\n * - `hasError`: Whether the last execution resulted in an error\n * - `isPending`: Whether the debouncer is waiting for the timeout to trigger execution\n * - `isExecuting`: Whether an async function execution is currently in progress\n * - `lastArgs`: The arguments from the most recent call to maybeExecute\n * - `lastError`: The error from the most recent failed execution (if any)\n * - `lastResult`: The result from the most recent successful execution\n * - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')\n *\n * ## Unmount behavior\n *\n * By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.\n * Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.\n * Use the `onUnmount` option to customize this. For example, to flush pending work instead:\n *\n * ```tsx\n * const debouncer = createAsyncDebouncer(fn, {\n * wait: 500,\n * onUnmount: (d) => d.flush()\n * });\n * ```\n *\n * Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.\n * If your debounced function updates Solid signals, those updates may run after the component has\n * unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when\n * using onUnmount with flush.\n *\n * @example\n * ```tsx\n * // Default behavior - no reactive state subscriptions\n * const { maybeExecute } = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 }\n * );\n *\n * // Opt-in to track isPending or isExecuting changes (optimized for loading states)\n * const debouncer = createAsyncDebouncer(\n * async (query: string) => {\n * const results = await api.search(query);\n * return results;\n * },\n * { wait: 500 },\n * (state) => ({ isPending: state.isPending, isExecuting: state.isExecuting })\n * );\n *\n * // Opt-in to track error state changes (optimized for error handling)\n * const debouncer = createAsyncDebouncer(\n * async (searchTerm) => {\n * const data = await searchAPI(searchTerm);\n * return data;\n * },\n * {\n * wait: 300,\n * leading: true, // Execute immediately on first call\n * trailing: false, // Skip trailing edge updates\n * onError: (error) => {\n * console.error('API call failed:', error);\n * }\n * },\n * (state) => ({ hasError: state.hasError, lastError: state.lastError })\n * );\n *\n * // Access the selected state (will be empty object {} unless selector provided)\n * const { isPending, isExecuting } = debouncer.state();\n * ```\n */\nexport function createAsyncDebouncer<\n TFn extends AnyAsyncFunction,\n TSelected = {},\n>(\n fn: TFn,\n options: SolidAsyncDebouncerOptions<TFn, TSelected>,\n selector: (state: AsyncDebouncerState<TFn>) => TSelected = () =>\n ({}) as TSelected,\n): SolidAsyncDebouncer<TFn, TSelected> {\n const mergedOptions = {\n ...useDefaultPacerOptions().asyncDebouncer,\n ...options,\n } as SolidAsyncDebouncerOptions<TFn, TSelected>\n const asyncDebouncer = new AsyncDebouncer<TFn>(\n fn,\n mergedOptions,\n ) as unknown as SolidAsyncDebouncer<TFn, TSelected>\n\n asyncDebouncer.Subscribe = function Subscribe<TSelected>(props: {\n selector: (state: AsyncDebouncerState<TFn>) => TSelected\n children: ((state: Accessor<TSelected>) => JSX.Element) | JSX.Element\n }) {\n const selected = useStore(asyncDebouncer.store, props.selector)\n\n return typeof props.children === 'function'\n ? props.children(selected)\n : props.children\n }\n\n const state = useStore(asyncDebouncer.store, selector)\n\n createEffect(() => {\n onCleanup(() => {\n if (mergedOptions.onUnmount) {\n mergedOptions.onUnmount(asyncDebouncer)\n } else {\n asyncDebouncer.cancel()\n asyncDebouncer.abort()\n }\n })\n })\n\n return {\n ...asyncDebouncer,\n state,\n } as SolidAsyncDebouncer<TFn, TSelected> // omit `store` in favor of `state`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8KA,SAAgB,qBAId,IACA,SACA,kBACG,EAAE,GACgC;CACrC,MAAM,gBAAgB;EACpB,GAAGA,8CAAwB,CAAC;EAC5B,GAAG;EACJ;CACD,MAAM,iBAAiB,IAAIC,+CACzB,IACA,cACD;AAED,gBAAe,YAAY,SAAS,UAAqB,OAGtD;EACD,MAAM,+CAAoB,eAAe,OAAO,MAAM,SAAS;AAE/D,SAAO,OAAO,MAAM,aAAa,aAC7B,MAAM,SAAS,SAAS,GACxB,MAAM;;CAGZ,MAAM,4CAAiB,eAAe,OAAO,SAAS;AAEtD,kCAAmB;AACjB,gCAAgB;AACd,OAAI,cAAc,UAChB,eAAc,UAAU,eAAe;QAClC;AACL,mBAAe,QAAQ;AACvB,mBAAe,OAAO;;IAExB;GACF;AAEF,QAAO;EACL,GAAG;EACH;EACD"}
|
|
@@ -4,6 +4,13 @@ import { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState } from "@tan
|
|
|
4
4
|
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
5
5
|
|
|
6
6
|
//#region src/async-debouncer/createAsyncDebouncer.d.ts
|
|
7
|
+
interface SolidAsyncDebouncerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncDebouncerOptions<TFn> {
|
|
8
|
+
/**
|
|
9
|
+
* Optional callback invoked when the owning component unmounts. Receives the debouncer instance.
|
|
10
|
+
* When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
|
|
11
|
+
*/
|
|
12
|
+
onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void;
|
|
13
|
+
}
|
|
7
14
|
interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncDebouncer<TFn>, 'store'> {
|
|
8
15
|
/**
|
|
9
16
|
* A Solid component that allows you to subscribe to the debouncer state.
|
|
@@ -91,6 +98,24 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
91
98
|
* - `lastResult`: The result from the most recent successful execution
|
|
92
99
|
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
|
|
93
100
|
*
|
|
101
|
+
* ## Unmount behavior
|
|
102
|
+
*
|
|
103
|
+
* By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
|
|
104
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
105
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
106
|
+
*
|
|
107
|
+
* ```tsx
|
|
108
|
+
* const debouncer = createAsyncDebouncer(fn, {
|
|
109
|
+
* wait: 500,
|
|
110
|
+
* onUnmount: (d) => d.flush()
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
115
|
+
* If your debounced function updates Solid signals, those updates may run after the component has
|
|
116
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
117
|
+
* using onUnmount with flush.
|
|
118
|
+
*
|
|
94
119
|
* @example
|
|
95
120
|
* ```tsx
|
|
96
121
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -133,7 +158,7 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
133
158
|
* const { isPending, isExecuting } = debouncer.state();
|
|
134
159
|
* ```
|
|
135
160
|
*/
|
|
136
|
-
declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options:
|
|
161
|
+
declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncDebouncerOptions<TFn, TSelected>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>;
|
|
137
162
|
//#endregion
|
|
138
|
-
export { SolidAsyncDebouncer, createAsyncDebouncer };
|
|
163
|
+
export { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer };
|
|
139
164
|
//# sourceMappingURL=createAsyncDebouncer.d.cts.map
|
|
@@ -4,6 +4,13 @@ import { AsyncDebouncer, AsyncDebouncerOptions, AsyncDebouncerState } from "@tan
|
|
|
4
4
|
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
5
5
|
|
|
6
6
|
//#region src/async-debouncer/createAsyncDebouncer.d.ts
|
|
7
|
+
interface SolidAsyncDebouncerOptions<TFn extends AnyAsyncFunction, TSelected = {}> extends AsyncDebouncerOptions<TFn> {
|
|
8
|
+
/**
|
|
9
|
+
* Optional callback invoked when the owning component unmounts. Receives the debouncer instance.
|
|
10
|
+
* When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
|
|
11
|
+
*/
|
|
12
|
+
onUnmount?: (debouncer: SolidAsyncDebouncer<TFn, TSelected>) => void;
|
|
13
|
+
}
|
|
7
14
|
interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> extends Omit<AsyncDebouncer<TFn>, 'store'> {
|
|
8
15
|
/**
|
|
9
16
|
* A Solid component that allows you to subscribe to the debouncer state.
|
|
@@ -91,6 +98,24 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
91
98
|
* - `lastResult`: The result from the most recent successful execution
|
|
92
99
|
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
|
|
93
100
|
*
|
|
101
|
+
* ## Unmount behavior
|
|
102
|
+
*
|
|
103
|
+
* By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning component unmounts.
|
|
104
|
+
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
105
|
+
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
106
|
+
*
|
|
107
|
+
* ```tsx
|
|
108
|
+
* const debouncer = createAsyncDebouncer(fn, {
|
|
109
|
+
* wait: 500,
|
|
110
|
+
* onUnmount: (d) => d.flush()
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
115
|
+
* If your debounced function updates Solid signals, those updates may run after the component has
|
|
116
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
117
|
+
* using onUnmount with flush.
|
|
118
|
+
*
|
|
94
119
|
* @example
|
|
95
120
|
* ```tsx
|
|
96
121
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -133,7 +158,7 @@ interface SolidAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}> exte
|
|
|
133
158
|
* const { isPending, isExecuting } = debouncer.state();
|
|
134
159
|
* ```
|
|
135
160
|
*/
|
|
136
|
-
declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options:
|
|
161
|
+
declare function createAsyncDebouncer<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: SolidAsyncDebouncerOptions<TFn, TSelected>, selector?: (state: AsyncDebouncerState<TFn>) => TSelected): SolidAsyncDebouncer<TFn, TSelected>;
|
|
137
162
|
//#endregion
|
|
138
|
-
export { SolidAsyncDebouncer, createAsyncDebouncer };
|
|
163
|
+
export { SolidAsyncDebouncer, SolidAsyncDebouncerOptions, createAsyncDebouncer };
|
|
139
164
|
//# sourceMappingURL=createAsyncDebouncer.d.ts.map
|
|
@@ -60,6 +60,24 @@ import { AsyncDebouncer } from "@tanstack/pacer/async-debouncer";
|
|
|
60
60
|
* - `lastResult`: The result from the most recent successful execution
|
|
61
61
|
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing')
|
|
62
62
|
*
|
|
63
|
+
* ## Unmount behavior
|
|
64
|
+
*
|
|
65
|
+
* By default, the primitive cancels any pending execution and aborts any in-flight execution when the owning 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 = createAsyncDebouncer(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 Solid signals, those updates may run after the component has
|
|
78
|
+
* unmounted, which can cause unexpected reactive updates. Guard your callbacks accordingly when
|
|
79
|
+
* using onUnmount with flush.
|
|
80
|
+
*
|
|
63
81
|
* @example
|
|
64
82
|
* ```tsx
|
|
65
83
|
* // Default behavior - no reactive state subscriptions
|
|
@@ -103,10 +121,11 @@ import { AsyncDebouncer } from "@tanstack/pacer/async-debouncer";
|
|
|
103
121
|
* ```
|
|
104
122
|
*/
|
|
105
123
|
function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
106
|
-
const
|
|
124
|
+
const mergedOptions = {
|
|
107
125
|
...useDefaultPacerOptions().asyncDebouncer,
|
|
108
126
|
...options
|
|
109
|
-
}
|
|
127
|
+
};
|
|
128
|
+
const asyncDebouncer = new AsyncDebouncer(fn, mergedOptions);
|
|
110
129
|
asyncDebouncer.Subscribe = function Subscribe(props) {
|
|
111
130
|
const selected = useStore(asyncDebouncer.store, props.selector);
|
|
112
131
|
return typeof props.children === "function" ? props.children(selected) : props.children;
|
|
@@ -114,7 +133,11 @@ function createAsyncDebouncer(fn, options, selector = () => ({})) {
|
|
|
114
133
|
const state = useStore(asyncDebouncer.store, selector);
|
|
115
134
|
createEffect(() => {
|
|
116
135
|
onCleanup(() => {
|
|
117
|
-
|
|
136
|
+
if (mergedOptions.onUnmount) mergedOptions.onUnmount(asyncDebouncer);
|
|
137
|
+
else {
|
|
138
|
+
asyncDebouncer.cancel();
|
|
139
|
+
asyncDebouncer.abort();
|
|
140
|
+
}
|
|
118
141
|
});
|
|
119
142
|
});
|
|
120
143
|
return {
|