@tanstack/preact-pacer 0.0.1 → 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/LICENSE +21 -0
- package/README.md +165 -45
- package/dist/async-batcher/index.cjs +12 -0
- package/dist/async-batcher/index.d.cts +4 -0
- package/dist/async-batcher/index.d.ts +4 -0
- package/dist/async-batcher/index.js +6 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +46 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js +51 -0
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.cjs +189 -0
- package/dist/async-batcher/useAsyncBatcher.cjs.map +1 -0
- package/dist/async-batcher/useAsyncBatcher.d.cts +198 -0
- package/dist/async-batcher/useAsyncBatcher.d.ts +198 -0
- package/dist/async-batcher/useAsyncBatcher.js +189 -0
- package/dist/async-batcher/useAsyncBatcher.js.map +1 -0
- package/dist/async-debouncer/index.cjs +12 -0
- package/dist/async-debouncer/index.d.cts +4 -0
- package/dist/async-debouncer/index.d.ts +4 -0
- package/dist/async-debouncer/index.js +6 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +47 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js +50 -0
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs +173 -0
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +1 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +178 -0
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +178 -0
- package/dist/async-debouncer/useAsyncDebouncer.js +173 -0
- package/dist/async-debouncer/useAsyncDebouncer.js.map +1 -0
- package/dist/async-queuer/index.cjs +12 -0
- package/dist/async-queuer/index.d.cts +4 -0
- package/dist/async-queuer/index.d.ts +4 -0
- package/dist/async-queuer/index.js +6 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs +154 -0
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuedState.d.cts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.d.ts +152 -0
- package/dist/async-queuer/useAsyncQueuedState.js +154 -0
- package/dist/async-queuer/useAsyncQueuedState.js.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.cjs +189 -0
- package/dist/async-queuer/useAsyncQueuer.cjs.map +1 -0
- package/dist/async-queuer/useAsyncQueuer.d.cts +198 -0
- package/dist/async-queuer/useAsyncQueuer.d.ts +198 -0
- package/dist/async-queuer/useAsyncQueuer.js +189 -0
- package/dist/async-queuer/useAsyncQueuer.js.map +1 -0
- package/dist/async-rate-limiter/index.cjs +12 -0
- package/dist/async-rate-limiter/index.d.cts +4 -0
- package/dist/async-rate-limiter/index.d.ts +4 -0
- package/dist/async-rate-limiter/index.js +6 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +62 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +65 -0
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +197 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +1 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +207 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +207 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +197 -0
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +1 -0
- package/dist/async-retryer/index.cjs +9 -0
- package/dist/async-retryer/index.d.cts +1 -0
- package/dist/async-retryer/index.d.ts +1 -0
- package/dist/async-retryer/index.js +3 -0
- package/dist/async-throttler/index.cjs +12 -0
- package/dist/async-throttler/index.d.cts +4 -0
- package/dist/async-throttler/index.d.ts +4 -0
- package/dist/async-throttler/index.js +6 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +45 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js +48 -0
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.cjs +182 -0
- package/dist/async-throttler/useAsyncThrottler.cjs.map +1 -0
- package/dist/async-throttler/useAsyncThrottler.d.cts +189 -0
- package/dist/async-throttler/useAsyncThrottler.d.ts +189 -0
- package/dist/async-throttler/useAsyncThrottler.js +182 -0
- package/dist/async-throttler/useAsyncThrottler.js.map +1 -0
- package/dist/batcher/index.cjs +12 -0
- package/dist/batcher/index.d.cts +4 -0
- package/dist/batcher/index.d.ts +4 -0
- package/dist/batcher/index.js +6 -0
- package/dist/batcher/useBatchedCallback.cjs +47 -0
- package/dist/batcher/useBatchedCallback.cjs.map +1 -0
- package/dist/batcher/useBatchedCallback.d.cts +44 -0
- package/dist/batcher/useBatchedCallback.d.ts +44 -0
- package/dist/batcher/useBatchedCallback.js +47 -0
- package/dist/batcher/useBatchedCallback.js.map +1 -0
- package/dist/batcher/useBatcher.cjs +146 -0
- package/dist/batcher/useBatcher.cjs.map +1 -0
- package/dist/batcher/useBatcher.d.cts +155 -0
- package/dist/batcher/useBatcher.d.ts +155 -0
- package/dist/batcher/useBatcher.js +146 -0
- package/dist/batcher/useBatcher.js.map +1 -0
- package/dist/debouncer/index.cjs +16 -0
- package/dist/debouncer/index.d.cts +6 -0
- package/dist/debouncer/index.d.ts +6 -0
- package/dist/debouncer/index.js +8 -0
- package/dist/debouncer/useDebouncedCallback.cjs +48 -0
- package/dist/debouncer/useDebouncedCallback.cjs.map +1 -0
- package/dist/debouncer/useDebouncedCallback.d.cts +45 -0
- package/dist/debouncer/useDebouncedCallback.d.ts +45 -0
- package/dist/debouncer/useDebouncedCallback.js +48 -0
- package/dist/debouncer/useDebouncedCallback.js.map +1 -0
- package/dist/debouncer/useDebouncedState.cjs +89 -0
- package/dist/debouncer/useDebouncedState.cjs.map +1 -0
- package/dist/debouncer/useDebouncedState.d.cts +82 -0
- package/dist/debouncer/useDebouncedState.d.ts +82 -0
- package/dist/debouncer/useDebouncedState.js +89 -0
- package/dist/debouncer/useDebouncedState.js.map +1 -0
- package/dist/debouncer/useDebouncedValue.cjs +96 -0
- package/dist/debouncer/useDebouncedValue.cjs.map +1 -0
- package/dist/debouncer/useDebouncedValue.d.cts +91 -0
- package/dist/debouncer/useDebouncedValue.d.ts +91 -0
- package/dist/debouncer/useDebouncedValue.js +96 -0
- package/dist/debouncer/useDebouncedValue.js.map +1 -0
- package/dist/debouncer/useDebouncer.cjs +128 -0
- package/dist/debouncer/useDebouncer.cjs.map +1 -0
- package/dist/debouncer/useDebouncer.d.cts +133 -0
- package/dist/debouncer/useDebouncer.d.ts +133 -0
- package/dist/debouncer/useDebouncer.js +128 -0
- package/dist/debouncer/useDebouncer.js.map +1 -0
- package/dist/index.cjs +66 -0
- package/dist/index.d.cts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +32 -0
- package/dist/provider/PacerProvider.cjs +26 -0
- package/dist/provider/PacerProvider.cjs.map +1 -0
- package/dist/provider/PacerProvider.d.cts +33 -0
- package/dist/provider/PacerProvider.d.ts +33 -0
- package/dist/provider/PacerProvider.js +24 -0
- package/dist/provider/PacerProvider.js.map +1 -0
- package/dist/provider/index.cjs +5 -0
- package/dist/provider/index.d.cts +2 -0
- package/dist/provider/index.d.ts +2 -0
- package/dist/provider/index.js +3 -0
- package/dist/queuer/index.cjs +14 -0
- package/dist/queuer/index.d.cts +5 -0
- package/dist/queuer/index.d.ts +5 -0
- package/dist/queuer/index.js +7 -0
- package/dist/queuer/useQueuedState.cjs +129 -0
- package/dist/queuer/useQueuedState.cjs.map +1 -0
- package/dist/queuer/useQueuedState.d.cts +123 -0
- package/dist/queuer/useQueuedState.d.ts +123 -0
- package/dist/queuer/useQueuedState.js +129 -0
- package/dist/queuer/useQueuedState.js.map +1 -0
- package/dist/queuer/useQueuedValue.cjs +115 -0
- package/dist/queuer/useQueuedValue.cjs.map +1 -0
- package/dist/queuer/useQueuedValue.d.cts +106 -0
- package/dist/queuer/useQueuedValue.d.ts +106 -0
- package/dist/queuer/useQueuedValue.js +115 -0
- package/dist/queuer/useQueuedValue.js.map +1 -0
- package/dist/queuer/useQueuer.cjs +157 -0
- package/dist/queuer/useQueuer.cjs.map +1 -0
- package/dist/queuer/useQueuer.d.cts +166 -0
- package/dist/queuer/useQueuer.d.ts +166 -0
- package/dist/queuer/useQueuer.js +157 -0
- package/dist/queuer/useQueuer.js.map +1 -0
- package/dist/rate-limiter/index.cjs +16 -0
- package/dist/rate-limiter/index.d.cts +6 -0
- package/dist/rate-limiter/index.d.ts +6 -0
- package/dist/rate-limiter/index.js +8 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +62 -0
- package/dist/rate-limiter/useRateLimitedCallback.js +65 -0
- package/dist/rate-limiter/useRateLimitedCallback.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.cjs +115 -0
- package/dist/rate-limiter/useRateLimitedState.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedState.d.cts +108 -0
- package/dist/rate-limiter/useRateLimitedState.d.ts +108 -0
- package/dist/rate-limiter/useRateLimitedState.js +115 -0
- package/dist/rate-limiter/useRateLimitedState.js.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs +102 -0
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimitedValue.d.cts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.d.ts +97 -0
- package/dist/rate-limiter/useRateLimitedValue.js +102 -0
- package/dist/rate-limiter/useRateLimitedValue.js.map +1 -0
- package/dist/rate-limiter/useRateLimiter.cjs +162 -0
- package/dist/rate-limiter/useRateLimiter.cjs.map +1 -0
- package/dist/rate-limiter/useRateLimiter.d.cts +172 -0
- package/dist/rate-limiter/useRateLimiter.d.ts +172 -0
- package/dist/rate-limiter/useRateLimiter.js +162 -0
- package/dist/rate-limiter/useRateLimiter.js.map +1 -0
- package/dist/throttler/index.cjs +16 -0
- package/dist/throttler/index.d.cts +6 -0
- package/dist/throttler/index.d.ts +6 -0
- package/dist/throttler/index.js +8 -0
- package/dist/throttler/useThrottledCallback.cjs +49 -0
- package/dist/throttler/useThrottledCallback.cjs.map +1 -0
- package/dist/throttler/useThrottledCallback.d.cts +46 -0
- package/dist/throttler/useThrottledCallback.d.ts +46 -0
- package/dist/throttler/useThrottledCallback.js +49 -0
- package/dist/throttler/useThrottledCallback.js.map +1 -0
- package/dist/throttler/useThrottledState.cjs +100 -0
- package/dist/throttler/useThrottledState.cjs.map +1 -0
- package/dist/throttler/useThrottledState.d.cts +93 -0
- package/dist/throttler/useThrottledState.d.ts +93 -0
- package/dist/throttler/useThrottledState.js +100 -0
- package/dist/throttler/useThrottledState.js.map +1 -0
- package/dist/throttler/useThrottledValue.cjs +91 -0
- package/dist/throttler/useThrottledValue.cjs.map +1 -0
- package/dist/throttler/useThrottledValue.d.cts +86 -0
- package/dist/throttler/useThrottledValue.d.ts +86 -0
- package/dist/throttler/useThrottledValue.js +91 -0
- package/dist/throttler/useThrottledValue.js.map +1 -0
- package/dist/throttler/useThrottler.cjs +133 -0
- package/dist/throttler/useThrottler.cjs.map +1 -0
- package/dist/throttler/useThrottler.d.cts +138 -0
- package/dist/throttler/useThrottler.d.ts +138 -0
- package/dist/throttler/useThrottler.js +133 -0
- package/dist/throttler/useThrottler.js.map +1 -0
- package/dist/types/index.cjs +9 -0
- package/dist/types/index.d.cts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +3 -0
- package/dist/utils/index.cjs +9 -0
- package/dist/utils/index.d.cts +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +3 -0
- package/package.json +118 -7
- package/src/async-batcher/index.ts +4 -0
- package/src/async-batcher/useAsyncBatchedCallback.ts +54 -0
- package/src/async-batcher/useAsyncBatcher.ts +249 -0
- package/src/async-debouncer/index.ts +5 -0
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +54 -0
- package/src/async-debouncer/useAsyncDebouncer.ts +235 -0
- package/src/async-queuer/index.ts +4 -0
- package/src/async-queuer/useAsyncQueuedState.ts +165 -0
- package/src/async-queuer/useAsyncQueuer.ts +249 -0
- package/src/async-rate-limiter/index.ts +5 -0
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +69 -0
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +261 -0
- package/src/async-retryer/index.ts +2 -0
- package/src/async-throttler/index.ts +5 -0
- package/src/async-throttler/useAsyncThrottledCallback.ts +52 -0
- package/src/async-throttler/useAsyncThrottler.ts +244 -0
- package/src/batcher/index.ts +4 -0
- package/src/batcher/useBatchedCallback.ts +50 -0
- package/src/batcher/useBatcher.ts +203 -0
- package/src/debouncer/index.ts +7 -0
- package/src/debouncer/useDebouncedCallback.ts +51 -0
- package/src/debouncer/useDebouncedState.ts +109 -0
- package/src/debouncer/useDebouncedValue.ts +112 -0
- package/src/debouncer/useDebouncer.ts +189 -0
- package/src/index.ts +56 -0
- package/src/provider/PacerProvider.tsx +70 -0
- package/src/provider/index.ts +1 -0
- package/src/queuer/index.ts +5 -0
- package/src/queuer/useQueuedState.ts +133 -0
- package/src/queuer/useQueuedValue.ts +129 -0
- package/src/queuer/useQueuer.ts +213 -0
- package/src/rate-limiter/index.ts +6 -0
- package/src/rate-limiter/useRateLimitedCallback.ts +68 -0
- package/src/rate-limiter/useRateLimitedState.ts +124 -0
- package/src/rate-limiter/useRateLimitedValue.ts +110 -0
- package/src/rate-limiter/useRateLimiter.ts +222 -0
- package/src/throttler/index.ts +7 -0
- package/src/throttler/useThrottledCallback.ts +52 -0
- package/src/throttler/useThrottledState.ts +121 -0
- package/src/throttler/useThrottledValue.ts +107 -0
- package/src/throttler/useThrottler.ts +194 -0
- package/src/types/index.ts +1 -0
- package/src/utils/index.ts +1 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
const require_PacerProvider = require('../provider/PacerProvider.cjs');
|
|
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");
|
|
5
|
+
|
|
6
|
+
//#region src/async-throttler/useAsyncThrottler.ts
|
|
7
|
+
/**
|
|
8
|
+
* A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
9
|
+
*
|
|
10
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
|
|
11
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
12
|
+
*
|
|
13
|
+
* Async throttling ensures an async function executes at most once within a specified time window,
|
|
14
|
+
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
15
|
+
* database operations, or other async tasks.
|
|
16
|
+
*
|
|
17
|
+
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
18
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
19
|
+
* instead of setting the result on a state variable from within the throttled function.
|
|
20
|
+
*
|
|
21
|
+
* Error Handling:
|
|
22
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
23
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
24
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
25
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
26
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
27
|
+
*
|
|
28
|
+
* ## State Management and Selector
|
|
29
|
+
*
|
|
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.
|
|
44
|
+
*
|
|
45
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
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.
|
|
48
|
+
*
|
|
49
|
+
* Available state properties:
|
|
50
|
+
* - `errorCount`: Number of function executions that have resulted in errors
|
|
51
|
+
* - `isExecuting`: Whether the throttled function is currently executing asynchronously
|
|
52
|
+
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
53
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
54
|
+
* - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
|
|
55
|
+
* - `lastResult`: The result from the most recent successful function execution
|
|
56
|
+
* - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
|
|
57
|
+
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
58
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
59
|
+
* - `successCount`: Number of function executions that have completed successfully
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```tsx
|
|
63
|
+
* // Default behavior - no reactive state subscriptions
|
|
64
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
65
|
+
* async (id: string) => {
|
|
66
|
+
* const data = await api.fetchData(id);
|
|
67
|
+
* return data; // Return value is preserved
|
|
68
|
+
* },
|
|
69
|
+
* { wait: 1000 }
|
|
70
|
+
* );
|
|
71
|
+
*
|
|
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)
|
|
80
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
81
|
+
* async (id: string) => {
|
|
82
|
+
* const data = await api.fetchData(id);
|
|
83
|
+
* return data;
|
|
84
|
+
* },
|
|
85
|
+
* { wait: 1000 },
|
|
86
|
+
* (state) => ({
|
|
87
|
+
* isExecuting: state.isExecuting,
|
|
88
|
+
* isPending: state.isPending,
|
|
89
|
+
* status: state.status
|
|
90
|
+
* })
|
|
91
|
+
* );
|
|
92
|
+
*
|
|
93
|
+
* // Opt-in to re-render when results are available (optimized for data display)
|
|
94
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
95
|
+
* async (id: string) => {
|
|
96
|
+
* const data = await api.fetchData(id);
|
|
97
|
+
* return data;
|
|
98
|
+
* },
|
|
99
|
+
* { wait: 1000 },
|
|
100
|
+
* (state) => ({
|
|
101
|
+
* lastResult: state.lastResult,
|
|
102
|
+
* successCount: state.successCount,
|
|
103
|
+
* settleCount: state.settleCount
|
|
104
|
+
* })
|
|
105
|
+
* );
|
|
106
|
+
*
|
|
107
|
+
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
108
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
109
|
+
* async (id: string) => {
|
|
110
|
+
* const data = await api.fetchData(id);
|
|
111
|
+
* return data;
|
|
112
|
+
* },
|
|
113
|
+
* {
|
|
114
|
+
* wait: 1000,
|
|
115
|
+
* onError: (error) => console.error('API call failed:', error)
|
|
116
|
+
* },
|
|
117
|
+
* (state) => ({
|
|
118
|
+
* errorCount: state.errorCount,
|
|
119
|
+
* status: state.status
|
|
120
|
+
* })
|
|
121
|
+
* );
|
|
122
|
+
*
|
|
123
|
+
* // Opt-in to re-render when timing information changes (optimized for timing displays)
|
|
124
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
125
|
+
* async (id: string) => {
|
|
126
|
+
* const data = await api.fetchData(id);
|
|
127
|
+
* return data;
|
|
128
|
+
* },
|
|
129
|
+
* { wait: 1000 },
|
|
130
|
+
* (state) => ({
|
|
131
|
+
* lastExecutionTime: state.lastExecutionTime,
|
|
132
|
+
* nextExecutionTime: state.nextExecutionTime
|
|
133
|
+
* })
|
|
134
|
+
* );
|
|
135
|
+
*
|
|
136
|
+
* // With state management and return value
|
|
137
|
+
* const [data, setData] = useState(null);
|
|
138
|
+
* const { maybeExecute, state } = useAsyncThrottler(
|
|
139
|
+
* async (query) => {
|
|
140
|
+
* const result = await searchAPI(query);
|
|
141
|
+
* setData(result);
|
|
142
|
+
* return result; // Return value can be used by the caller
|
|
143
|
+
* },
|
|
144
|
+
* {
|
|
145
|
+
* wait: 2000,
|
|
146
|
+
* leading: true, // Execute immediately on first call
|
|
147
|
+
* trailing: false // Skip trailing edge updates
|
|
148
|
+
* }
|
|
149
|
+
* );
|
|
150
|
+
*
|
|
151
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
152
|
+
* const { isExecuting, lastResult } = state;
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
function useAsyncThrottler(fn, options, selector = () => ({})) {
|
|
156
|
+
const mergedOptions = {
|
|
157
|
+
...require_PacerProvider.useDefaultPacerOptions().asyncThrottler,
|
|
158
|
+
...options
|
|
159
|
+
};
|
|
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
|
+
});
|
|
168
|
+
asyncThrottler.fn = fn;
|
|
169
|
+
asyncThrottler.setOptions(mergedOptions);
|
|
170
|
+
const state = (0, _tanstack_preact_store.useStore)(asyncThrottler.store, selector);
|
|
171
|
+
(0, preact_hooks.useEffect)(() => {
|
|
172
|
+
return () => asyncThrottler.cancel();
|
|
173
|
+
}, [asyncThrottler]);
|
|
174
|
+
return (0, preact_hooks.useMemo)(() => ({
|
|
175
|
+
...asyncThrottler,
|
|
176
|
+
state
|
|
177
|
+
}), [asyncThrottler, state]);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
//#endregion
|
|
181
|
+
exports.useAsyncThrottler = useAsyncThrottler;
|
|
182
|
+
//# sourceMappingURL=useAsyncThrottler.cjs.map
|
|
@@ -0,0 +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'\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"}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { Store } from "@tanstack/preact-store";
|
|
2
|
+
import { ComponentChildren } from "preact";
|
|
3
|
+
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
4
|
+
import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler";
|
|
5
|
+
|
|
6
|
+
//#region src/async-throttler/useAsyncThrottler.d.ts
|
|
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;
|
|
25
|
+
/**
|
|
26
|
+
* Reactive state that will be updated and re-rendered when the throttler state changes
|
|
27
|
+
*
|
|
28
|
+
* Use this instead of `throttler.store.state`
|
|
29
|
+
*/
|
|
30
|
+
readonly state: Readonly<TSelected>;
|
|
31
|
+
/**
|
|
32
|
+
* @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
|
|
33
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
34
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
35
|
+
*/
|
|
36
|
+
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
40
|
+
*
|
|
41
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
|
|
42
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
43
|
+
*
|
|
44
|
+
* Async throttling ensures an async function executes at most once within a specified time window,
|
|
45
|
+
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
46
|
+
* database operations, or other async tasks.
|
|
47
|
+
*
|
|
48
|
+
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
49
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
50
|
+
* instead of setting the result on a state variable from within the throttled function.
|
|
51
|
+
*
|
|
52
|
+
* Error Handling:
|
|
53
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
54
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
55
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
56
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
57
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
58
|
+
*
|
|
59
|
+
* ## State Management and Selector
|
|
60
|
+
*
|
|
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.
|
|
75
|
+
*
|
|
76
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
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.
|
|
79
|
+
*
|
|
80
|
+
* Available state properties:
|
|
81
|
+
* - `errorCount`: Number of function executions that have resulted in errors
|
|
82
|
+
* - `isExecuting`: Whether the throttled function is currently executing asynchronously
|
|
83
|
+
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
84
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
85
|
+
* - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
|
|
86
|
+
* - `lastResult`: The result from the most recent successful function execution
|
|
87
|
+
* - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
|
|
88
|
+
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
89
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
90
|
+
* - `successCount`: Number of function executions that have completed successfully
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```tsx
|
|
94
|
+
* // Default behavior - no reactive state subscriptions
|
|
95
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
96
|
+
* async (id: string) => {
|
|
97
|
+
* const data = await api.fetchData(id);
|
|
98
|
+
* return data; // Return value is preserved
|
|
99
|
+
* },
|
|
100
|
+
* { wait: 1000 }
|
|
101
|
+
* );
|
|
102
|
+
*
|
|
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)
|
|
111
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
112
|
+
* async (id: string) => {
|
|
113
|
+
* const data = await api.fetchData(id);
|
|
114
|
+
* return data;
|
|
115
|
+
* },
|
|
116
|
+
* { wait: 1000 },
|
|
117
|
+
* (state) => ({
|
|
118
|
+
* isExecuting: state.isExecuting,
|
|
119
|
+
* isPending: state.isPending,
|
|
120
|
+
* status: state.status
|
|
121
|
+
* })
|
|
122
|
+
* );
|
|
123
|
+
*
|
|
124
|
+
* // Opt-in to re-render when results are available (optimized for data display)
|
|
125
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
126
|
+
* async (id: string) => {
|
|
127
|
+
* const data = await api.fetchData(id);
|
|
128
|
+
* return data;
|
|
129
|
+
* },
|
|
130
|
+
* { wait: 1000 },
|
|
131
|
+
* (state) => ({
|
|
132
|
+
* lastResult: state.lastResult,
|
|
133
|
+
* successCount: state.successCount,
|
|
134
|
+
* settleCount: state.settleCount
|
|
135
|
+
* })
|
|
136
|
+
* );
|
|
137
|
+
*
|
|
138
|
+
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
139
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
140
|
+
* async (id: string) => {
|
|
141
|
+
* const data = await api.fetchData(id);
|
|
142
|
+
* return data;
|
|
143
|
+
* },
|
|
144
|
+
* {
|
|
145
|
+
* wait: 1000,
|
|
146
|
+
* onError: (error) => console.error('API call failed:', error)
|
|
147
|
+
* },
|
|
148
|
+
* (state) => ({
|
|
149
|
+
* errorCount: state.errorCount,
|
|
150
|
+
* status: state.status
|
|
151
|
+
* })
|
|
152
|
+
* );
|
|
153
|
+
*
|
|
154
|
+
* // Opt-in to re-render when timing information changes (optimized for timing displays)
|
|
155
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
156
|
+
* async (id: string) => {
|
|
157
|
+
* const data = await api.fetchData(id);
|
|
158
|
+
* return data;
|
|
159
|
+
* },
|
|
160
|
+
* { wait: 1000 },
|
|
161
|
+
* (state) => ({
|
|
162
|
+
* lastExecutionTime: state.lastExecutionTime,
|
|
163
|
+
* nextExecutionTime: state.nextExecutionTime
|
|
164
|
+
* })
|
|
165
|
+
* );
|
|
166
|
+
*
|
|
167
|
+
* // With state management and return value
|
|
168
|
+
* const [data, setData] = useState(null);
|
|
169
|
+
* const { maybeExecute, state } = useAsyncThrottler(
|
|
170
|
+
* async (query) => {
|
|
171
|
+
* const result = await searchAPI(query);
|
|
172
|
+
* setData(result);
|
|
173
|
+
* return result; // Return value can be used by the caller
|
|
174
|
+
* },
|
|
175
|
+
* {
|
|
176
|
+
* wait: 2000,
|
|
177
|
+
* leading: true, // Execute immediately on first call
|
|
178
|
+
* trailing: false // Skip trailing edge updates
|
|
179
|
+
* }
|
|
180
|
+
* );
|
|
181
|
+
*
|
|
182
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
183
|
+
* const { isExecuting, lastResult } = state;
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): PreactAsyncThrottler<TFn, TSelected>;
|
|
187
|
+
//#endregion
|
|
188
|
+
export { PreactAsyncThrottler, useAsyncThrottler };
|
|
189
|
+
//# sourceMappingURL=useAsyncThrottler.d.cts.map
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { ComponentChildren } from "preact";
|
|
2
|
+
import { Store } from "@tanstack/preact-store";
|
|
3
|
+
import { AsyncThrottler, AsyncThrottlerOptions, AsyncThrottlerState } from "@tanstack/pacer/async-throttler";
|
|
4
|
+
import { AnyAsyncFunction } from "@tanstack/pacer/types";
|
|
5
|
+
|
|
6
|
+
//#region src/async-throttler/useAsyncThrottler.d.ts
|
|
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;
|
|
25
|
+
/**
|
|
26
|
+
* Reactive state that will be updated and re-rendered when the throttler state changes
|
|
27
|
+
*
|
|
28
|
+
* Use this instead of `throttler.store.state`
|
|
29
|
+
*/
|
|
30
|
+
readonly state: Readonly<TSelected>;
|
|
31
|
+
/**
|
|
32
|
+
* @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
|
|
33
|
+
* The state on the store object is not reactive, as it has not been wrapped in a `useStore` hook internally.
|
|
34
|
+
* Although, you can make the state reactive by using the `useStore` in your own usage.
|
|
35
|
+
*/
|
|
36
|
+
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
40
|
+
*
|
|
41
|
+
* This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
|
|
42
|
+
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
43
|
+
*
|
|
44
|
+
* Async throttling ensures an async function executes at most once within a specified time window,
|
|
45
|
+
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
46
|
+
* database operations, or other async tasks.
|
|
47
|
+
*
|
|
48
|
+
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
49
|
+
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
50
|
+
* instead of setting the result on a state variable from within the throttled function.
|
|
51
|
+
*
|
|
52
|
+
* Error Handling:
|
|
53
|
+
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
54
|
+
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
55
|
+
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
56
|
+
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
57
|
+
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
58
|
+
*
|
|
59
|
+
* ## State Management and Selector
|
|
60
|
+
*
|
|
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.
|
|
75
|
+
*
|
|
76
|
+
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
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.
|
|
79
|
+
*
|
|
80
|
+
* Available state properties:
|
|
81
|
+
* - `errorCount`: Number of function executions that have resulted in errors
|
|
82
|
+
* - `isExecuting`: Whether the throttled function is currently executing asynchronously
|
|
83
|
+
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
84
|
+
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
85
|
+
* - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
|
|
86
|
+
* - `lastResult`: The result from the most recent successful function execution
|
|
87
|
+
* - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
|
|
88
|
+
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
89
|
+
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
90
|
+
* - `successCount`: Number of function executions that have completed successfully
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```tsx
|
|
94
|
+
* // Default behavior - no reactive state subscriptions
|
|
95
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
96
|
+
* async (id: string) => {
|
|
97
|
+
* const data = await api.fetchData(id);
|
|
98
|
+
* return data; // Return value is preserved
|
|
99
|
+
* },
|
|
100
|
+
* { wait: 1000 }
|
|
101
|
+
* );
|
|
102
|
+
*
|
|
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)
|
|
111
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
112
|
+
* async (id: string) => {
|
|
113
|
+
* const data = await api.fetchData(id);
|
|
114
|
+
* return data;
|
|
115
|
+
* },
|
|
116
|
+
* { wait: 1000 },
|
|
117
|
+
* (state) => ({
|
|
118
|
+
* isExecuting: state.isExecuting,
|
|
119
|
+
* isPending: state.isPending,
|
|
120
|
+
* status: state.status
|
|
121
|
+
* })
|
|
122
|
+
* );
|
|
123
|
+
*
|
|
124
|
+
* // Opt-in to re-render when results are available (optimized for data display)
|
|
125
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
126
|
+
* async (id: string) => {
|
|
127
|
+
* const data = await api.fetchData(id);
|
|
128
|
+
* return data;
|
|
129
|
+
* },
|
|
130
|
+
* { wait: 1000 },
|
|
131
|
+
* (state) => ({
|
|
132
|
+
* lastResult: state.lastResult,
|
|
133
|
+
* successCount: state.successCount,
|
|
134
|
+
* settleCount: state.settleCount
|
|
135
|
+
* })
|
|
136
|
+
* );
|
|
137
|
+
*
|
|
138
|
+
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
139
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
140
|
+
* async (id: string) => {
|
|
141
|
+
* const data = await api.fetchData(id);
|
|
142
|
+
* return data;
|
|
143
|
+
* },
|
|
144
|
+
* {
|
|
145
|
+
* wait: 1000,
|
|
146
|
+
* onError: (error) => console.error('API call failed:', error)
|
|
147
|
+
* },
|
|
148
|
+
* (state) => ({
|
|
149
|
+
* errorCount: state.errorCount,
|
|
150
|
+
* status: state.status
|
|
151
|
+
* })
|
|
152
|
+
* );
|
|
153
|
+
*
|
|
154
|
+
* // Opt-in to re-render when timing information changes (optimized for timing displays)
|
|
155
|
+
* const asyncThrottler = useAsyncThrottler(
|
|
156
|
+
* async (id: string) => {
|
|
157
|
+
* const data = await api.fetchData(id);
|
|
158
|
+
* return data;
|
|
159
|
+
* },
|
|
160
|
+
* { wait: 1000 },
|
|
161
|
+
* (state) => ({
|
|
162
|
+
* lastExecutionTime: state.lastExecutionTime,
|
|
163
|
+
* nextExecutionTime: state.nextExecutionTime
|
|
164
|
+
* })
|
|
165
|
+
* );
|
|
166
|
+
*
|
|
167
|
+
* // With state management and return value
|
|
168
|
+
* const [data, setData] = useState(null);
|
|
169
|
+
* const { maybeExecute, state } = useAsyncThrottler(
|
|
170
|
+
* async (query) => {
|
|
171
|
+
* const result = await searchAPI(query);
|
|
172
|
+
* setData(result);
|
|
173
|
+
* return result; // Return value can be used by the caller
|
|
174
|
+
* },
|
|
175
|
+
* {
|
|
176
|
+
* wait: 2000,
|
|
177
|
+
* leading: true, // Execute immediately on first call
|
|
178
|
+
* trailing: false // Skip trailing edge updates
|
|
179
|
+
* }
|
|
180
|
+
* );
|
|
181
|
+
*
|
|
182
|
+
* // Access the selected state (will be empty object {} unless selector provided)
|
|
183
|
+
* const { isExecuting, lastResult } = state;
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
declare function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(fn: TFn, options: AsyncThrottlerOptions<TFn>, selector?: (state: AsyncThrottlerState<TFn>) => TSelected): PreactAsyncThrottler<TFn, TSelected>;
|
|
187
|
+
//#endregion
|
|
188
|
+
export { PreactAsyncThrottler, useAsyncThrottler };
|
|
189
|
+
//# sourceMappingURL=useAsyncThrottler.d.ts.map
|