@tanstack/preact-pacer 0.22.1 → 0.24.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 +17 -2
- package/dist/async-batcher/useAsyncBatchedCallback.d.ts +2 -5
- package/dist/async-batcher/useAsyncBatchedCallback.js +1 -2
- package/dist/async-batcher/useAsyncBatcher.d.ts +4 -8
- package/dist/async-batcher/useAsyncBatcher.js +1 -3
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.ts +6 -7
- package/dist/async-debouncer/useAsyncDebouncedCallback.js +5 -4
- package/dist/async-debouncer/useAsyncDebouncer.d.ts +4 -7
- package/dist/async-debouncer/useAsyncDebouncer.js +1 -2
- package/dist/async-queuer/useAsyncQueuedState.d.ts +4 -7
- package/dist/async-queuer/useAsyncQueuedState.js +3 -4
- package/dist/async-queuer/useAsyncQueuer.d.ts +6 -9
- package/dist/async-queuer/useAsyncQueuer.js +3 -4
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.ts +2 -5
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js +1 -2
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.ts +4 -7
- package/dist/async-rate-limiter/useAsyncRateLimiter.js +1 -2
- package/dist/async-throttler/useAsyncThrottledCallback.d.ts +7 -9
- package/dist/async-throttler/useAsyncThrottledCallback.js +6 -6
- package/dist/async-throttler/useAsyncThrottler.d.ts +4 -7
- package/dist/async-throttler/useAsyncThrottler.js +1 -2
- package/dist/batcher/useBatchedCallback.d.ts +2 -5
- package/dist/batcher/useBatchedCallback.js +1 -2
- package/dist/batcher/useBatcher.d.ts +6 -11
- package/dist/batcher/useBatcher.js +3 -6
- package/dist/debouncer/useDebouncedCallback.d.ts +2 -5
- package/dist/debouncer/useDebouncedCallback.js +1 -2
- package/dist/debouncer/useDebouncedState.d.ts +2 -5
- package/dist/debouncer/useDebouncedState.js +1 -2
- package/dist/debouncer/useDebouncedValue.d.ts +2 -5
- package/dist/debouncer/useDebouncedValue.js +1 -2
- package/dist/debouncer/useDebouncer.d.ts +4 -7
- package/dist/debouncer/useDebouncer.js +1 -2
- package/dist/provider/PacerProvider.d.ts +6 -13
- package/dist/provider/PacerProvider.js +1 -2
- package/dist/queuer/useQueuedState.d.ts +2 -5
- package/dist/queuer/useQueuedState.js +1 -2
- package/dist/queuer/useQueuedValue.d.ts +2 -5
- package/dist/queuer/useQueuedValue.js +1 -2
- package/dist/queuer/useQueuer.d.ts +4 -7
- package/dist/queuer/useQueuer.js +1 -2
- package/dist/rate-limiter/useRateLimitedCallback.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedCallback.js +1 -2
- package/dist/rate-limiter/useRateLimitedState.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedState.js +1 -2
- package/dist/rate-limiter/useRateLimitedValue.d.ts +2 -5
- package/dist/rate-limiter/useRateLimitedValue.js +1 -2
- package/dist/rate-limiter/useRateLimiter.d.ts +4 -7
- package/dist/rate-limiter/useRateLimiter.js +1 -2
- package/dist/throttler/useThrottledCallback.d.ts +2 -5
- package/dist/throttler/useThrottledCallback.js +1 -2
- package/dist/throttler/useThrottledState.d.ts +2 -5
- package/dist/throttler/useThrottledState.js +1 -2
- package/dist/throttler/useThrottledValue.d.ts +2 -5
- package/dist/throttler/useThrottledValue.js +1 -2
- package/dist/throttler/useThrottler.d.ts +4 -7
- package/dist/throttler/useThrottler.js +1 -2
- package/package.json +24 -72
- package/dist/async-batcher/index.cjs +0 -13
- package/dist/async-batcher/index.d.cts +0 -4
- package/dist/async-batcher/useAsyncBatchedCallback.cjs +0 -51
- package/dist/async-batcher/useAsyncBatchedCallback.cjs.map +0 -1
- package/dist/async-batcher/useAsyncBatchedCallback.d.cts +0 -44
- package/dist/async-batcher/useAsyncBatchedCallback.js.map +0 -1
- package/dist/async-batcher/useAsyncBatcher.cjs +0 -217
- package/dist/async-batcher/useAsyncBatcher.cjs.map +0 -1
- package/dist/async-batcher/useAsyncBatcher.d.cts +0 -224
- package/dist/async-batcher/useAsyncBatcher.js.map +0 -1
- package/dist/async-debouncer/index.cjs +0 -13
- package/dist/async-debouncer/index.d.cts +0 -4
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs +0 -50
- package/dist/async-debouncer/useAsyncDebouncedCallback.cjs.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncedCallback.d.cts +0 -46
- package/dist/async-debouncer/useAsyncDebouncedCallback.js.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncer.cjs +0 -195
- package/dist/async-debouncer/useAsyncDebouncer.cjs.map +0 -1
- package/dist/async-debouncer/useAsyncDebouncer.d.cts +0 -203
- package/dist/async-debouncer/useAsyncDebouncer.js.map +0 -1
- package/dist/async-queuer/index.cjs +0 -13
- package/dist/async-queuer/index.d.cts +0 -4
- package/dist/async-queuer/useAsyncQueuedState.cjs +0 -154
- package/dist/async-queuer/useAsyncQueuedState.cjs.map +0 -1
- package/dist/async-queuer/useAsyncQueuedState.d.cts +0 -151
- package/dist/async-queuer/useAsyncQueuedState.js.map +0 -1
- package/dist/async-queuer/useAsyncQueuer.cjs +0 -217
- package/dist/async-queuer/useAsyncQueuer.cjs.map +0 -1
- package/dist/async-queuer/useAsyncQueuer.d.cts +0 -224
- package/dist/async-queuer/useAsyncQueuer.js.map +0 -1
- package/dist/async-rate-limiter/index.cjs +0 -13
- package/dist/async-rate-limiter/index.d.cts +0 -4
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs +0 -65
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.cjs.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.d.cts +0 -61
- package/dist/async-rate-limiter/useAsyncRateLimitedCallback.js.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs +0 -209
- package/dist/async-rate-limiter/useAsyncRateLimiter.cjs.map +0 -1
- package/dist/async-rate-limiter/useAsyncRateLimiter.d.cts +0 -220
- package/dist/async-rate-limiter/useAsyncRateLimiter.js.map +0 -1
- package/dist/async-retryer/index.cjs +0 -9
- package/dist/async-retryer/index.d.cts +0 -1
- package/dist/async-throttler/index.cjs +0 -13
- package/dist/async-throttler/index.d.cts +0 -4
- package/dist/async-throttler/useAsyncThrottledCallback.cjs +0 -48
- package/dist/async-throttler/useAsyncThrottledCallback.cjs.map +0 -1
- package/dist/async-throttler/useAsyncThrottledCallback.d.cts +0 -44
- package/dist/async-throttler/useAsyncThrottledCallback.js.map +0 -1
- package/dist/async-throttler/useAsyncThrottler.cjs +0 -206
- package/dist/async-throttler/useAsyncThrottler.cjs.map +0 -1
- package/dist/async-throttler/useAsyncThrottler.d.cts +0 -214
- package/dist/async-throttler/useAsyncThrottler.js.map +0 -1
- package/dist/batcher/index.cjs +0 -13
- package/dist/batcher/index.d.cts +0 -4
- package/dist/batcher/useBatchedCallback.cjs +0 -47
- package/dist/batcher/useBatchedCallback.cjs.map +0 -1
- package/dist/batcher/useBatchedCallback.d.cts +0 -42
- package/dist/batcher/useBatchedCallback.js.map +0 -1
- package/dist/batcher/useBatcher.cjs +0 -165
- package/dist/batcher/useBatcher.cjs.map +0 -1
- package/dist/batcher/useBatcher.d.cts +0 -175
- package/dist/batcher/useBatcher.js.map +0 -1
- package/dist/debouncer/index.cjs +0 -17
- package/dist/debouncer/index.d.cts +0 -6
- package/dist/debouncer/useDebouncedCallback.cjs +0 -48
- package/dist/debouncer/useDebouncedCallback.cjs.map +0 -1
- package/dist/debouncer/useDebouncedCallback.d.cts +0 -44
- package/dist/debouncer/useDebouncedCallback.js.map +0 -1
- package/dist/debouncer/useDebouncedState.cjs +0 -89
- package/dist/debouncer/useDebouncedState.cjs.map +0 -1
- package/dist/debouncer/useDebouncedState.d.cts +0 -81
- package/dist/debouncer/useDebouncedState.js.map +0 -1
- package/dist/debouncer/useDebouncedValue.cjs +0 -96
- package/dist/debouncer/useDebouncedValue.cjs.map +0 -1
- package/dist/debouncer/useDebouncedValue.d.cts +0 -90
- package/dist/debouncer/useDebouncedValue.js.map +0 -1
- package/dist/debouncer/useDebouncer.cjs +0 -141
- package/dist/debouncer/useDebouncer.cjs.map +0 -1
- package/dist/debouncer/useDebouncer.d.cts +0 -152
- package/dist/debouncer/useDebouncer.js.map +0 -1
- package/dist/index.cjs +0 -67
- package/dist/index.d.cts +0 -30
- package/dist/provider/PacerProvider.cjs +0 -26
- package/dist/provider/PacerProvider.cjs.map +0 -1
- package/dist/provider/PacerProvider.d.cts +0 -33
- package/dist/provider/PacerProvider.js.map +0 -1
- package/dist/provider/index.cjs +0 -6
- package/dist/provider/index.d.cts +0 -2
- package/dist/queuer/index.cjs +0 -15
- package/dist/queuer/index.d.cts +0 -5
- package/dist/queuer/useQueuedState.cjs +0 -129
- package/dist/queuer/useQueuedState.cjs.map +0 -1
- package/dist/queuer/useQueuedState.d.cts +0 -122
- package/dist/queuer/useQueuedState.js.map +0 -1
- package/dist/queuer/useQueuedValue.cjs +0 -115
- package/dist/queuer/useQueuedValue.cjs.map +0 -1
- package/dist/queuer/useQueuedValue.d.cts +0 -105
- package/dist/queuer/useQueuedValue.js.map +0 -1
- package/dist/queuer/useQueuer.cjs +0 -176
- package/dist/queuer/useQueuer.cjs.map +0 -1
- package/dist/queuer/useQueuer.d.cts +0 -186
- package/dist/queuer/useQueuer.js.map +0 -1
- package/dist/rate-limiter/index.cjs +0 -17
- package/dist/rate-limiter/index.d.cts +0 -6
- package/dist/rate-limiter/useRateLimitedCallback.cjs +0 -65
- package/dist/rate-limiter/useRateLimitedCallback.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedCallback.d.cts +0 -61
- package/dist/rate-limiter/useRateLimitedCallback.js.map +0 -1
- package/dist/rate-limiter/useRateLimitedState.cjs +0 -115
- package/dist/rate-limiter/useRateLimitedState.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedState.d.cts +0 -107
- package/dist/rate-limiter/useRateLimitedState.js.map +0 -1
- package/dist/rate-limiter/useRateLimitedValue.cjs +0 -102
- package/dist/rate-limiter/useRateLimitedValue.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimitedValue.d.cts +0 -96
- package/dist/rate-limiter/useRateLimitedValue.js.map +0 -1
- package/dist/rate-limiter/useRateLimiter.cjs +0 -167
- package/dist/rate-limiter/useRateLimiter.cjs.map +0 -1
- package/dist/rate-limiter/useRateLimiter.d.cts +0 -179
- package/dist/rate-limiter/useRateLimiter.js.map +0 -1
- package/dist/throttler/index.cjs +0 -17
- package/dist/throttler/index.d.cts +0 -6
- package/dist/throttler/useThrottledCallback.cjs +0 -49
- package/dist/throttler/useThrottledCallback.cjs.map +0 -1
- package/dist/throttler/useThrottledCallback.d.cts +0 -45
- package/dist/throttler/useThrottledCallback.js.map +0 -1
- package/dist/throttler/useThrottledState.cjs +0 -100
- package/dist/throttler/useThrottledState.cjs.map +0 -1
- package/dist/throttler/useThrottledState.d.cts +0 -92
- package/dist/throttler/useThrottledState.js.map +0 -1
- package/dist/throttler/useThrottledValue.cjs +0 -91
- package/dist/throttler/useThrottledValue.cjs.map +0 -1
- package/dist/throttler/useThrottledValue.d.cts +0 -85
- package/dist/throttler/useThrottledValue.js.map +0 -1
- package/dist/throttler/useThrottler.cjs +0 -146
- package/dist/throttler/useThrottler.cjs.map +0 -1
- package/dist/throttler/useThrottler.d.cts +0 -157
- package/dist/throttler/useThrottler.js.map +0 -1
- package/dist/types/index.cjs +0 -9
- package/dist/types/index.d.cts +0 -1
- package/dist/utils/index.cjs +0 -9
- package/dist/utils/index.d.cts +0 -1
- package/src/async-batcher/index.ts +0 -4
- package/src/async-batcher/useAsyncBatchedCallback.ts +0 -53
- package/src/async-batcher/useAsyncBatcher.ts +0 -293
- package/src/async-debouncer/index.ts +0 -5
- package/src/async-debouncer/useAsyncDebouncedCallback.ts +0 -54
- package/src/async-debouncer/useAsyncDebouncer.ts +0 -274
- package/src/async-queuer/index.ts +0 -4
- package/src/async-queuer/useAsyncQueuedState.ts +0 -165
- package/src/async-queuer/useAsyncQueuer.ts +0 -293
- package/src/async-rate-limiter/index.ts +0 -5
- package/src/async-rate-limiter/useAsyncRateLimitedCallback.ts +0 -69
- package/src/async-rate-limiter/useAsyncRateLimiter.ts +0 -294
- package/src/async-retryer/index.ts +0 -2
- package/src/async-throttler/index.ts +0 -5
- package/src/async-throttler/useAsyncThrottledCallback.ts +0 -52
- package/src/async-throttler/useAsyncThrottler.ts +0 -285
- package/src/batcher/index.ts +0 -4
- package/src/batcher/useBatchedCallback.ts +0 -46
- package/src/batcher/useBatcher.ts +0 -241
- package/src/debouncer/index.ts +0 -7
- package/src/debouncer/useDebouncedCallback.ts +0 -51
- package/src/debouncer/useDebouncedState.ts +0 -106
- package/src/debouncer/useDebouncedValue.ts +0 -109
- package/src/debouncer/useDebouncer.ts +0 -219
- package/src/index.ts +0 -56
- package/src/provider/PacerProvider.tsx +0 -70
- package/src/provider/index.ts +0 -1
- package/src/queuer/index.ts +0 -5
- package/src/queuer/useQueuedState.ts +0 -133
- package/src/queuer/useQueuedValue.ts +0 -129
- package/src/queuer/useQueuer.ts +0 -251
- package/src/rate-limiter/index.ts +0 -6
- package/src/rate-limiter/useRateLimitedCallback.ts +0 -68
- package/src/rate-limiter/useRateLimitedState.ts +0 -124
- package/src/rate-limiter/useRateLimitedValue.ts +0 -110
- package/src/rate-limiter/useRateLimiter.ts +0 -244
- package/src/throttler/index.ts +0 -7
- package/src/throttler/useThrottledCallback.ts +0 -52
- package/src/throttler/useThrottledState.ts +0 -118
- package/src/throttler/useThrottledValue.ts +0 -104
- package/src/throttler/useThrottler.ts +0 -224
- package/src/types/index.ts +0 -1
- package/src/utils/index.ts +0 -1
|
@@ -1,294 +0,0 @@
|
|
|
1
|
-
import { useEffect, useMemo, useState } from 'preact/hooks'
|
|
2
|
-
import { AsyncRateLimiter } from '@tanstack/pacer/async-rate-limiter'
|
|
3
|
-
import { shallow, useSelector } from '@tanstack/preact-store'
|
|
4
|
-
import { useDefaultPacerOptions } from '../provider/PacerProvider'
|
|
5
|
-
import type { Store } from '@tanstack/preact-store'
|
|
6
|
-
import type { AnyAsyncFunction } from '@tanstack/pacer/types'
|
|
7
|
-
import type {
|
|
8
|
-
AsyncRateLimiterOptions,
|
|
9
|
-
AsyncRateLimiterState,
|
|
10
|
-
} from '@tanstack/pacer/async-rate-limiter'
|
|
11
|
-
import type { ComponentChildren } from 'preact'
|
|
12
|
-
|
|
13
|
-
export interface PreactAsyncRateLimiterOptions<
|
|
14
|
-
TFn extends AnyAsyncFunction,
|
|
15
|
-
TSelected = {},
|
|
16
|
-
> extends AsyncRateLimiterOptions<TFn> {
|
|
17
|
-
/**
|
|
18
|
-
* Optional callback invoked when the component unmounts. Receives the rate limiter instance.
|
|
19
|
-
* When provided, replaces the default cleanup (abort); use it to call reset(), add logging, etc.
|
|
20
|
-
*/
|
|
21
|
-
onUnmount?: (rateLimiter: PreactAsyncRateLimiter<TFn, TSelected>) => void
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface PreactAsyncRateLimiter<
|
|
25
|
-
TFn extends AnyAsyncFunction,
|
|
26
|
-
TSelected = {},
|
|
27
|
-
> extends Omit<AsyncRateLimiter<TFn>, 'store'> {
|
|
28
|
-
/**
|
|
29
|
-
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async rate limiter state.
|
|
30
|
-
*
|
|
31
|
-
* This is useful for opting into state re-renders for specific parts of the rate limiter state
|
|
32
|
-
* deep in your component tree without needing to pass a selector to the hook.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* <rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
36
|
-
* {({ rejectionCount }) => (
|
|
37
|
-
* <div>Rejections: {rejectionCount}</div>
|
|
38
|
-
* )}
|
|
39
|
-
* </rateLimiter.Subscribe>
|
|
40
|
-
*/
|
|
41
|
-
Subscribe: <TSelected>(props: {
|
|
42
|
-
selector: (state: AsyncRateLimiterState<TFn>) => TSelected
|
|
43
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
44
|
-
}) => ComponentChildren
|
|
45
|
-
/**
|
|
46
|
-
* Reactive state that will be updated and re-rendered when the rate limiter state changes
|
|
47
|
-
*
|
|
48
|
-
* Use this instead of `rateLimiter.store.state`
|
|
49
|
-
*/
|
|
50
|
-
readonly state: Readonly<TSelected>
|
|
51
|
-
/**
|
|
52
|
-
* @deprecated Use `rateLimiter.state` instead of `rateLimiter.store.state` if you want to read reactive state.
|
|
53
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
54
|
-
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
55
|
-
*/
|
|
56
|
-
readonly store: Store<Readonly<AsyncRateLimiterState<TFn>>>
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* A low-level Preact hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.
|
|
61
|
-
*
|
|
62
|
-
* This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
|
|
63
|
-
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
64
|
-
*
|
|
65
|
-
* Rate limiting allows an async function to execute up to a specified limit within a time window,
|
|
66
|
-
* then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,
|
|
67
|
-
* managing resource constraints, or controlling bursts of async operations.
|
|
68
|
-
*
|
|
69
|
-
* Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
|
|
70
|
-
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
71
|
-
* instead of setting the result on a state variable from within the rate-limited function.
|
|
72
|
-
*
|
|
73
|
-
* The rate limiter supports two types of windows:
|
|
74
|
-
* - 'fixed': A strict window that resets after the window period. All executions within the window count
|
|
75
|
-
* towards the limit, and the window resets completely after the period.
|
|
76
|
-
* - 'sliding': A rolling window that allows executions as old ones expire. This provides a more
|
|
77
|
-
* consistent rate of execution over time.
|
|
78
|
-
*
|
|
79
|
-
* Error Handling:
|
|
80
|
-
* - If an `onError` handler is provided, it will be called with the error and rate limiter instance
|
|
81
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
82
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
83
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
84
|
-
* - The error state can be checked using the underlying AsyncRateLimiter instance
|
|
85
|
-
* - Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
|
|
86
|
-
*
|
|
87
|
-
* ## State Management and Selector
|
|
88
|
-
*
|
|
89
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
90
|
-
* in two ways:
|
|
91
|
-
*
|
|
92
|
-
* **1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
93
|
-
*
|
|
94
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
95
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
96
|
-
* in child components.
|
|
97
|
-
*
|
|
98
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
99
|
-
*
|
|
100
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
101
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
102
|
-
* state changes occur.
|
|
103
|
-
*
|
|
104
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
105
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
106
|
-
* re-renders and gives you full control over when your component updates.
|
|
107
|
-
*
|
|
108
|
-
* Available state properties:
|
|
109
|
-
* - `errorCount`: Number of function executions that have resulted in errors
|
|
110
|
-
* - `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
|
|
111
|
-
* - `isExecuting`: Whether the rate-limited function is currently executing asynchronously
|
|
112
|
-
* - `lastResult`: The result from the most recent successful function execution
|
|
113
|
-
* - `rejectionCount`: Number of function executions that have been rejected due to rate limiting
|
|
114
|
-
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
115
|
-
* - `successCount`: Number of function executions that have completed successfully
|
|
116
|
-
*
|
|
117
|
-
* ## Unmount behavior
|
|
118
|
-
*
|
|
119
|
-
* By default, the hook aborts any in-flight execution when the component unmounts.
|
|
120
|
-
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
121
|
-
* Use the `onUnmount` option to customize this.
|
|
122
|
-
*
|
|
123
|
-
* @example
|
|
124
|
-
* ```tsx
|
|
125
|
-
* // Default behavior - no reactive state subscriptions
|
|
126
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
127
|
-
* async (id: string) => {
|
|
128
|
-
* const data = await api.fetchData(id);
|
|
129
|
-
* return data; // Return value is preserved
|
|
130
|
-
* },
|
|
131
|
-
* { limit: 5, window: 1000 } // 5 calls per second
|
|
132
|
-
* );
|
|
133
|
-
*
|
|
134
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
135
|
-
* <asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
|
|
136
|
-
* {({ rejectionCount }) => (
|
|
137
|
-
* <div>Rejections: {rejectionCount}</div>
|
|
138
|
-
* )}
|
|
139
|
-
* </asyncRateLimiter.Subscribe>
|
|
140
|
-
*
|
|
141
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
142
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
143
|
-
* async (id: string) => {
|
|
144
|
-
* const data = await api.fetchData(id);
|
|
145
|
-
* return data;
|
|
146
|
-
* },
|
|
147
|
-
* { limit: 5, window: 1000 },
|
|
148
|
-
* (state) => ({ isExecuting: state.isExecuting })
|
|
149
|
-
* );
|
|
150
|
-
*
|
|
151
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
152
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
153
|
-
* async (id: string) => {
|
|
154
|
-
* const data = await api.fetchData(id);
|
|
155
|
-
* return data;
|
|
156
|
-
* },
|
|
157
|
-
* { limit: 5, window: 1000 },
|
|
158
|
-
* (state) => ({
|
|
159
|
-
* lastResult: state.lastResult,
|
|
160
|
-
* successCount: state.successCount
|
|
161
|
-
* })
|
|
162
|
-
* );
|
|
163
|
-
*
|
|
164
|
-
* // Opt-in to re-render when error/rejection state changes (optimized for error handling)
|
|
165
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
166
|
-
* async (id: string) => {
|
|
167
|
-
* const data = await api.fetchData(id);
|
|
168
|
-
* return data;
|
|
169
|
-
* },
|
|
170
|
-
* {
|
|
171
|
-
* limit: 5,
|
|
172
|
-
* window: 1000,
|
|
173
|
-
* onError: (error) => console.error('API call failed:', error),
|
|
174
|
-
* onReject: (rateLimiter) => console.log('Rate limit exceeded')
|
|
175
|
-
* },
|
|
176
|
-
* (state) => ({
|
|
177
|
-
* errorCount: state.errorCount,
|
|
178
|
-
* rejectionCount: state.rejectionCount
|
|
179
|
-
* })
|
|
180
|
-
* );
|
|
181
|
-
*
|
|
182
|
-
* // Opt-in to re-render when execution metrics change (optimized for stats display)
|
|
183
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
184
|
-
* async (id: string) => {
|
|
185
|
-
* const data = await api.fetchData(id);
|
|
186
|
-
* return data;
|
|
187
|
-
* },
|
|
188
|
-
* { limit: 5, window: 1000 },
|
|
189
|
-
* (state) => ({
|
|
190
|
-
* successCount: state.successCount,
|
|
191
|
-
* errorCount: state.errorCount,
|
|
192
|
-
* settleCount: state.settleCount,
|
|
193
|
-
* rejectionCount: state.rejectionCount
|
|
194
|
-
* })
|
|
195
|
-
* );
|
|
196
|
-
*
|
|
197
|
-
* // Opt-in to re-render when execution times change (optimized for window calculations)
|
|
198
|
-
* const asyncRateLimiter = useAsyncRateLimiter(
|
|
199
|
-
* async (id: string) => {
|
|
200
|
-
* const data = await api.fetchData(id);
|
|
201
|
-
* return data;
|
|
202
|
-
* },
|
|
203
|
-
* { limit: 5, window: 1000 },
|
|
204
|
-
* (state) => ({ executionTimes: state.executionTimes })
|
|
205
|
-
* );
|
|
206
|
-
*
|
|
207
|
-
* // With state management and return value
|
|
208
|
-
* const [data, setData] = useState(null);
|
|
209
|
-
* const { maybeExecute, state } = useAsyncRateLimiter(
|
|
210
|
-
* async (query) => {
|
|
211
|
-
* const result = await searchAPI(query);
|
|
212
|
-
* setData(result);
|
|
213
|
-
* return result; // Return value can be used by the caller
|
|
214
|
-
* },
|
|
215
|
-
* {
|
|
216
|
-
* limit: 10,
|
|
217
|
-
* window: 60000, // 10 calls per minute
|
|
218
|
-
* onReject: (rateLimiter) => {
|
|
219
|
-
* console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
|
|
220
|
-
* },
|
|
221
|
-
* onError: (error) => {
|
|
222
|
-
* console.error('API call failed:', error);
|
|
223
|
-
* }
|
|
224
|
-
* }
|
|
225
|
-
* );
|
|
226
|
-
*
|
|
227
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
228
|
-
* const { isExecuting, lastResult, rejectionCount } = state;
|
|
229
|
-
* ```
|
|
230
|
-
*/
|
|
231
|
-
export function useAsyncRateLimiter<
|
|
232
|
-
TFn extends AnyAsyncFunction,
|
|
233
|
-
TSelected = {},
|
|
234
|
-
>(
|
|
235
|
-
fn: TFn,
|
|
236
|
-
options: PreactAsyncRateLimiterOptions<TFn, TSelected>,
|
|
237
|
-
selector: (state: AsyncRateLimiterState<TFn>) => TSelected = () =>
|
|
238
|
-
({}) as TSelected,
|
|
239
|
-
): PreactAsyncRateLimiter<TFn, TSelected> {
|
|
240
|
-
const mergedOptions = {
|
|
241
|
-
...useDefaultPacerOptions().asyncRateLimiter,
|
|
242
|
-
...options,
|
|
243
|
-
} as PreactAsyncRateLimiterOptions<TFn, TSelected>
|
|
244
|
-
|
|
245
|
-
const [asyncRateLimiter] = useState(() => {
|
|
246
|
-
const rateLimiterInstance = new AsyncRateLimiter<TFn>(
|
|
247
|
-
fn,
|
|
248
|
-
mergedOptions,
|
|
249
|
-
) as unknown as PreactAsyncRateLimiter<TFn, TSelected>
|
|
250
|
-
|
|
251
|
-
rateLimiterInstance.Subscribe = function Subscribe<TSelected>(props: {
|
|
252
|
-
selector: (state: AsyncRateLimiterState<TFn>) => TSelected
|
|
253
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
254
|
-
}) {
|
|
255
|
-
const selected = useSelector(rateLimiterInstance.store, props.selector, {
|
|
256
|
-
compare: shallow,
|
|
257
|
-
})
|
|
258
|
-
|
|
259
|
-
return typeof props.children === 'function'
|
|
260
|
-
? props.children(selected)
|
|
261
|
-
: props.children
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
return rateLimiterInstance
|
|
265
|
-
})
|
|
266
|
-
|
|
267
|
-
asyncRateLimiter.fn = fn
|
|
268
|
-
asyncRateLimiter.setOptions(mergedOptions)
|
|
269
|
-
|
|
270
|
-
/* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */
|
|
271
|
-
useEffect(() => {
|
|
272
|
-
return () => {
|
|
273
|
-
if (mergedOptions.onUnmount) {
|
|
274
|
-
mergedOptions.onUnmount(asyncRateLimiter)
|
|
275
|
-
} else {
|
|
276
|
-
asyncRateLimiter.abort()
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}, [])
|
|
280
|
-
/* eslint-enable react-hooks/exhaustive-deps */
|
|
281
|
-
|
|
282
|
-
const state = useSelector(asyncRateLimiter.store, selector, {
|
|
283
|
-
compare: shallow,
|
|
284
|
-
})
|
|
285
|
-
|
|
286
|
-
return useMemo(
|
|
287
|
-
() =>
|
|
288
|
-
({
|
|
289
|
-
...asyncRateLimiter,
|
|
290
|
-
state,
|
|
291
|
-
}) as PreactAsyncRateLimiter<TFn, TSelected>, // omit `store` in favor of `state`
|
|
292
|
-
[asyncRateLimiter, state],
|
|
293
|
-
)
|
|
294
|
-
}
|
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import { useCallback } from 'preact/hooks'
|
|
2
|
-
import { useAsyncThrottler } from './useAsyncThrottler'
|
|
3
|
-
import type { PreactAsyncThrottlerOptions } from './useAsyncThrottler'
|
|
4
|
-
import type { AnyAsyncFunction } from '@tanstack/pacer/types'
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* A Preact hook that creates a throttled version of an async callback function.
|
|
8
|
-
* This hook is a convenient wrapper around the `useAsyncThrottler` hook,
|
|
9
|
-
* providing a stable, throttled async function reference for use in Preact components.
|
|
10
|
-
*
|
|
11
|
-
* The throttled async function will execute at most once within the specified wait time period,
|
|
12
|
-
* regardless of how many times it is called. If called multiple times during the wait period,
|
|
13
|
-
* only the first invocation will execute, and subsequent calls will be ignored until
|
|
14
|
-
* the wait period has elapsed. The returned function always returns a promise
|
|
15
|
-
* that resolves or rejects with the result of the original async function.
|
|
16
|
-
*
|
|
17
|
-
* This hook provides a simpler API compared to `useAsyncThrottler`, making it ideal for basic
|
|
18
|
-
* async throttling needs. However, it does not expose the underlying AsyncThrottler instance.
|
|
19
|
-
*
|
|
20
|
-
* For advanced usage requiring features like:
|
|
21
|
-
* - Manual cancellation
|
|
22
|
-
* - Access to execution/error state
|
|
23
|
-
* - Custom useCallback dependencies
|
|
24
|
-
*
|
|
25
|
-
* Consider using the `useAsyncThrottler` hook instead.
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* @example
|
|
29
|
-
* ```tsx
|
|
30
|
-
* // Throttle an async API call
|
|
31
|
-
* const handleApiCall = useAsyncThrottledCallback(async (data) => {
|
|
32
|
-
* const result = await sendDataToServer(data);
|
|
33
|
-
* return result;
|
|
34
|
-
* }, {
|
|
35
|
-
* wait: 200 // Execute at most once every 200ms
|
|
36
|
-
* });
|
|
37
|
-
*
|
|
38
|
-
* // Use in an event handler
|
|
39
|
-
* <button onClick={() => handleApiCall(formData)}>Send</button>
|
|
40
|
-
* ```
|
|
41
|
-
*/
|
|
42
|
-
export function useAsyncThrottledCallback<TFn extends AnyAsyncFunction>(
|
|
43
|
-
fn: TFn,
|
|
44
|
-
options: PreactAsyncThrottlerOptions<TFn, {}>,
|
|
45
|
-
): (...args: Parameters<TFn>) => Promise<ReturnType<TFn>> {
|
|
46
|
-
const asyncThrottledFn = useAsyncThrottler(fn, options).maybeExecute
|
|
47
|
-
return useCallback(
|
|
48
|
-
(...args: Parameters<TFn>) =>
|
|
49
|
-
asyncThrottledFn(...args) as Promise<ReturnType<TFn>>,
|
|
50
|
-
[asyncThrottledFn],
|
|
51
|
-
)
|
|
52
|
-
}
|
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
import { useEffect, useMemo, useState } from 'preact/hooks'
|
|
2
|
-
import { AsyncThrottler } from '@tanstack/pacer/async-throttler'
|
|
3
|
-
import { shallow, useSelector } from '@tanstack/preact-store'
|
|
4
|
-
import { useDefaultPacerOptions } from '../provider/PacerProvider'
|
|
5
|
-
import type { Store } from '@tanstack/preact-store'
|
|
6
|
-
import type { AnyAsyncFunction } from '@tanstack/pacer/types'
|
|
7
|
-
import type {
|
|
8
|
-
AsyncThrottlerOptions,
|
|
9
|
-
AsyncThrottlerState,
|
|
10
|
-
} from '@tanstack/pacer/async-throttler'
|
|
11
|
-
import type { ComponentChildren } from 'preact'
|
|
12
|
-
|
|
13
|
-
export interface PreactAsyncThrottlerOptions<
|
|
14
|
-
TFn extends AnyAsyncFunction,
|
|
15
|
-
TSelected = {},
|
|
16
|
-
> extends AsyncThrottlerOptions<TFn> {
|
|
17
|
-
/**
|
|
18
|
-
* Optional callback invoked when the component unmounts. Receives the throttler instance.
|
|
19
|
-
* When provided, replaces the default cleanup (cancel + abort); use it to call flush(), reset(), cancel(), add logging, etc.
|
|
20
|
-
*/
|
|
21
|
-
onUnmount?: (throttler: PreactAsyncThrottler<TFn, TSelected>) => void
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
export interface PreactAsyncThrottler<
|
|
25
|
-
TFn extends AnyAsyncFunction,
|
|
26
|
-
TSelected = {},
|
|
27
|
-
> extends Omit<AsyncThrottler<TFn>, 'store'> {
|
|
28
|
-
/**
|
|
29
|
-
* A Preact HOC (Higher Order Component) that allows you to subscribe to the async throttler state.
|
|
30
|
-
*
|
|
31
|
-
* This is useful for opting into state re-renders for specific parts of the throttler state
|
|
32
|
-
* deep in your component tree without needing to pass a selector to the hook.
|
|
33
|
-
*
|
|
34
|
-
* @example
|
|
35
|
-
* <throttler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
36
|
-
* {({ isPending }) => (
|
|
37
|
-
* <div>{isPending ? 'Loading...' : 'Ready'}</div>
|
|
38
|
-
* )}
|
|
39
|
-
* </throttler.Subscribe>
|
|
40
|
-
*/
|
|
41
|
-
Subscribe: <TSelected>(props: {
|
|
42
|
-
selector: (state: AsyncThrottlerState<TFn>) => TSelected
|
|
43
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
44
|
-
}) => ComponentChildren
|
|
45
|
-
/**
|
|
46
|
-
* Reactive state that will be updated and re-rendered when the throttler state changes
|
|
47
|
-
*
|
|
48
|
-
* Use this instead of `throttler.store.state`
|
|
49
|
-
*/
|
|
50
|
-
readonly state: Readonly<TSelected>
|
|
51
|
-
/**
|
|
52
|
-
* @deprecated Use `throttler.state` instead of `throttler.store.state` if you want to read reactive state.
|
|
53
|
-
* The state on the store object is not reactive, as it has not been wrapped in a `useSelector` hook internally.
|
|
54
|
-
* Although, you can make the state reactive by using the `useSelector` in your own usage.
|
|
55
|
-
*/
|
|
56
|
-
readonly store: Store<Readonly<AsyncThrottlerState<TFn>>>
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* A low-level Preact hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
|
|
61
|
-
*
|
|
62
|
-
* This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
|
|
63
|
-
* you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
|
|
64
|
-
*
|
|
65
|
-
* Async throttling ensures an async function executes at most once within a specified time window,
|
|
66
|
-
* regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
|
|
67
|
-
* database operations, or other async tasks.
|
|
68
|
-
*
|
|
69
|
-
* Unlike the non-async Throttler, this async version supports returning values from the throttled function,
|
|
70
|
-
* making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
|
|
71
|
-
* instead of setting the result on a state variable from within the throttled function.
|
|
72
|
-
*
|
|
73
|
-
* Error Handling:
|
|
74
|
-
* - If an `onError` handler is provided, it will be called with the error and throttler instance
|
|
75
|
-
* - If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
|
|
76
|
-
* - If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
|
|
77
|
-
* - Both onError and throwOnError can be used together - the handler will be called before any error is thrown
|
|
78
|
-
* - The error state can be checked using the underlying AsyncThrottler instance
|
|
79
|
-
*
|
|
80
|
-
* ## State Management and Selector
|
|
81
|
-
*
|
|
82
|
-
* The hook uses TanStack Store for reactive state management. You can subscribe to state changes
|
|
83
|
-
* in two ways:
|
|
84
|
-
*
|
|
85
|
-
* **1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
|
|
86
|
-
*
|
|
87
|
-
* Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
|
|
88
|
-
* needing to pass a selector to the hook. This is ideal when you want to subscribe to state
|
|
89
|
-
* in child components.
|
|
90
|
-
*
|
|
91
|
-
* **2. Using the `selector` parameter (For hook-level subscriptions)**
|
|
92
|
-
*
|
|
93
|
-
* The `selector` parameter allows you to specify which state changes will trigger a re-render
|
|
94
|
-
* at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
|
|
95
|
-
* state changes occur.
|
|
96
|
-
*
|
|
97
|
-
* **By default, there will be no reactive state subscriptions** and you must opt-in to state
|
|
98
|
-
* tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
|
|
99
|
-
* re-renders and gives you full control over when your component updates.
|
|
100
|
-
*
|
|
101
|
-
* Available state properties:
|
|
102
|
-
* - `errorCount`: Number of function executions that have resulted in errors
|
|
103
|
-
* - `isExecuting`: Whether the throttled function is currently executing asynchronously
|
|
104
|
-
* - `isPending`: Whether the throttler is waiting for the timeout to trigger execution
|
|
105
|
-
* - `lastArgs`: The arguments from the most recent call to maybeExecute
|
|
106
|
-
* - `lastExecutionTime`: Timestamp of the last function execution in milliseconds
|
|
107
|
-
* - `lastResult`: The result from the most recent successful function execution
|
|
108
|
-
* - `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
|
|
109
|
-
* - `settleCount`: Number of function executions that have completed (success or error)
|
|
110
|
-
* - `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
|
|
111
|
-
* - `successCount`: Number of function executions that have completed successfully
|
|
112
|
-
*
|
|
113
|
-
* ## Unmount behavior
|
|
114
|
-
*
|
|
115
|
-
* By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.
|
|
116
|
-
* Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
|
|
117
|
-
* Use the `onUnmount` option to customize this. For example, to flush pending work instead:
|
|
118
|
-
*
|
|
119
|
-
* ```tsx
|
|
120
|
-
* const throttler = useAsyncThrottler(fn, {
|
|
121
|
-
* wait: 1000,
|
|
122
|
-
* onUnmount: (t) => t.flush()
|
|
123
|
-
* });
|
|
124
|
-
* ```
|
|
125
|
-
*
|
|
126
|
-
* Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
|
|
127
|
-
* If your throttled function updates Preact state, those updates may run after the component has
|
|
128
|
-
* unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
|
|
129
|
-
* accordingly when using onUnmount with flush.
|
|
130
|
-
*
|
|
131
|
-
* @example
|
|
132
|
-
* ```tsx
|
|
133
|
-
* // Default behavior - no reactive state subscriptions
|
|
134
|
-
* const asyncThrottler = useAsyncThrottler(
|
|
135
|
-
* async (id: string) => {
|
|
136
|
-
* const data = await api.fetchData(id);
|
|
137
|
-
* return data; // Return value is preserved
|
|
138
|
-
* },
|
|
139
|
-
* { wait: 1000 }
|
|
140
|
-
* );
|
|
141
|
-
*
|
|
142
|
-
* // Subscribe to state changes deep in component tree using Subscribe HOC
|
|
143
|
-
* <asyncThrottler.Subscribe selector={(state) => ({ isPending: state.isPending })}>
|
|
144
|
-
* {({ isPending }) => (
|
|
145
|
-
* <div>{isPending ? 'Processing...' : 'Ready'}</div>
|
|
146
|
-
* )}
|
|
147
|
-
* </asyncThrottler.Subscribe>
|
|
148
|
-
*
|
|
149
|
-
* // Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
|
|
150
|
-
* const asyncThrottler = useAsyncThrottler(
|
|
151
|
-
* async (id: string) => {
|
|
152
|
-
* const data = await api.fetchData(id);
|
|
153
|
-
* return data;
|
|
154
|
-
* },
|
|
155
|
-
* { wait: 1000 },
|
|
156
|
-
* (state) => ({
|
|
157
|
-
* isExecuting: state.isExecuting,
|
|
158
|
-
* isPending: state.isPending,
|
|
159
|
-
* status: state.status
|
|
160
|
-
* })
|
|
161
|
-
* );
|
|
162
|
-
*
|
|
163
|
-
* // Opt-in to re-render when results are available (optimized for data display)
|
|
164
|
-
* const asyncThrottler = useAsyncThrottler(
|
|
165
|
-
* async (id: string) => {
|
|
166
|
-
* const data = await api.fetchData(id);
|
|
167
|
-
* return data;
|
|
168
|
-
* },
|
|
169
|
-
* { wait: 1000 },
|
|
170
|
-
* (state) => ({
|
|
171
|
-
* lastResult: state.lastResult,
|
|
172
|
-
* successCount: state.successCount,
|
|
173
|
-
* settleCount: state.settleCount
|
|
174
|
-
* })
|
|
175
|
-
* );
|
|
176
|
-
*
|
|
177
|
-
* // Opt-in to re-render when error state changes (optimized for error handling)
|
|
178
|
-
* const asyncThrottler = useAsyncThrottler(
|
|
179
|
-
* async (id: string) => {
|
|
180
|
-
* const data = await api.fetchData(id);
|
|
181
|
-
* return data;
|
|
182
|
-
* },
|
|
183
|
-
* {
|
|
184
|
-
* wait: 1000,
|
|
185
|
-
* onError: (error) => console.error('API call failed:', error)
|
|
186
|
-
* },
|
|
187
|
-
* (state) => ({
|
|
188
|
-
* errorCount: state.errorCount,
|
|
189
|
-
* status: state.status
|
|
190
|
-
* })
|
|
191
|
-
* );
|
|
192
|
-
*
|
|
193
|
-
* // Opt-in to re-render when timing information changes (optimized for timing displays)
|
|
194
|
-
* const asyncThrottler = useAsyncThrottler(
|
|
195
|
-
* async (id: string) => {
|
|
196
|
-
* const data = await api.fetchData(id);
|
|
197
|
-
* return data;
|
|
198
|
-
* },
|
|
199
|
-
* { wait: 1000 },
|
|
200
|
-
* (state) => ({
|
|
201
|
-
* lastExecutionTime: state.lastExecutionTime,
|
|
202
|
-
* nextExecutionTime: state.nextExecutionTime
|
|
203
|
-
* })
|
|
204
|
-
* );
|
|
205
|
-
*
|
|
206
|
-
* // With state management and return value
|
|
207
|
-
* const [data, setData] = useState(null);
|
|
208
|
-
* const { maybeExecute, state } = useAsyncThrottler(
|
|
209
|
-
* async (query) => {
|
|
210
|
-
* const result = await searchAPI(query);
|
|
211
|
-
* setData(result);
|
|
212
|
-
* return result; // Return value can be used by the caller
|
|
213
|
-
* },
|
|
214
|
-
* {
|
|
215
|
-
* wait: 2000,
|
|
216
|
-
* leading: true, // Execute immediately on first call
|
|
217
|
-
* trailing: false // Skip trailing edge updates
|
|
218
|
-
* }
|
|
219
|
-
* );
|
|
220
|
-
*
|
|
221
|
-
* // Access the selected state (will be empty object {} unless selector provided)
|
|
222
|
-
* const { isExecuting, lastResult } = state;
|
|
223
|
-
* ```
|
|
224
|
-
*/
|
|
225
|
-
export function useAsyncThrottler<TFn extends AnyAsyncFunction, TSelected = {}>(
|
|
226
|
-
fn: TFn,
|
|
227
|
-
options: PreactAsyncThrottlerOptions<TFn, TSelected>,
|
|
228
|
-
selector: (state: AsyncThrottlerState<TFn>) => TSelected = () =>
|
|
229
|
-
({}) as TSelected,
|
|
230
|
-
): PreactAsyncThrottler<TFn, TSelected> {
|
|
231
|
-
const mergedOptions = {
|
|
232
|
-
...useDefaultPacerOptions().asyncThrottler,
|
|
233
|
-
...options,
|
|
234
|
-
} as PreactAsyncThrottlerOptions<TFn, TSelected>
|
|
235
|
-
const [asyncThrottler] = useState(() => {
|
|
236
|
-
const throttlerInstance = new AsyncThrottler<TFn>(
|
|
237
|
-
fn,
|
|
238
|
-
mergedOptions,
|
|
239
|
-
) as unknown as PreactAsyncThrottler<TFn, TSelected>
|
|
240
|
-
|
|
241
|
-
throttlerInstance.Subscribe = function Subscribe<TSelected>(props: {
|
|
242
|
-
selector: (state: AsyncThrottlerState<TFn>) => TSelected
|
|
243
|
-
children: ((state: TSelected) => ComponentChildren) | ComponentChildren
|
|
244
|
-
}) {
|
|
245
|
-
const selected = useSelector(throttlerInstance.store, props.selector, {
|
|
246
|
-
compare: shallow,
|
|
247
|
-
})
|
|
248
|
-
|
|
249
|
-
return typeof props.children === 'function'
|
|
250
|
-
? props.children(selected)
|
|
251
|
-
: props.children
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
return throttlerInstance
|
|
255
|
-
})
|
|
256
|
-
|
|
257
|
-
asyncThrottler.fn = fn
|
|
258
|
-
asyncThrottler.setOptions(mergedOptions)
|
|
259
|
-
|
|
260
|
-
const state = useSelector(asyncThrottler.store, selector, {
|
|
261
|
-
compare: shallow,
|
|
262
|
-
})
|
|
263
|
-
|
|
264
|
-
/* eslint-disable react-hooks/exhaustive-deps -- cleanup only; runs on unmount */
|
|
265
|
-
useEffect(() => {
|
|
266
|
-
return () => {
|
|
267
|
-
if (mergedOptions.onUnmount) {
|
|
268
|
-
mergedOptions.onUnmount(asyncThrottler)
|
|
269
|
-
} else {
|
|
270
|
-
asyncThrottler.cancel()
|
|
271
|
-
asyncThrottler.abort()
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
}, [])
|
|
275
|
-
/* eslint-enable react-hooks/exhaustive-deps */
|
|
276
|
-
|
|
277
|
-
return useMemo(
|
|
278
|
-
() =>
|
|
279
|
-
({
|
|
280
|
-
...asyncThrottler,
|
|
281
|
-
state,
|
|
282
|
-
}) as PreactAsyncThrottler<TFn, TSelected>, // omit `store` in favor of `state`
|
|
283
|
-
[asyncThrottler, state],
|
|
284
|
-
)
|
|
285
|
-
}
|
package/src/batcher/index.ts
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { useCallback } from 'preact/hooks'
|
|
2
|
-
import { useBatcher } from './useBatcher'
|
|
3
|
-
import type { PreactBatcherOptions } from './useBatcher'
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* A Preact hook that creates a batched version of a callback function.
|
|
7
|
-
* This hook is essentially a wrapper around the basic `batch` function
|
|
8
|
-
* that is exported from `@tanstack/pacer`,
|
|
9
|
-
* but optimized for Preact with reactive options and a stable function reference.
|
|
10
|
-
*
|
|
11
|
-
* The batched function will collect individual calls into batches and execute them
|
|
12
|
-
* when batch conditions are met (max size reached, wait time elapsed, or custom logic).
|
|
13
|
-
*
|
|
14
|
-
* This hook provides a simpler API compared to `useBatcher`, making it ideal for basic
|
|
15
|
-
* batching needs. However, it does not expose the underlying Batcher instance.
|
|
16
|
-
*
|
|
17
|
-
* For advanced usage requiring features like:
|
|
18
|
-
* - Manual batch execution
|
|
19
|
-
* - Access to batch state and metrics
|
|
20
|
-
* - Custom useCallback dependencies
|
|
21
|
-
*
|
|
22
|
-
* Consider using the `useBatcher` hook instead.
|
|
23
|
-
*
|
|
24
|
-
* @example
|
|
25
|
-
* ```tsx
|
|
26
|
-
* // Batch analytics events
|
|
27
|
-
* const trackEvents = useBatchedCallback((events: AnalyticsEvent[]) => {
|
|
28
|
-
* sendAnalytics(events);
|
|
29
|
-
* }, {
|
|
30
|
-
* maxSize: 5, // Process when 5 events collected
|
|
31
|
-
* wait: 2000 // Or after 2 seconds
|
|
32
|
-
* });
|
|
33
|
-
*
|
|
34
|
-
* // Use in event handlers
|
|
35
|
-
* <button onClick={() => trackEvents({ type: 'click', target: 'button' })}>
|
|
36
|
-
* Click me
|
|
37
|
-
* </button>
|
|
38
|
-
* ```
|
|
39
|
-
*/
|
|
40
|
-
export function useBatchedCallback<TValue>(
|
|
41
|
-
fn: (items: Array<TValue>) => void,
|
|
42
|
-
options: PreactBatcherOptions<TValue, {}>,
|
|
43
|
-
): (item: TValue) => void {
|
|
44
|
-
const batchedFn = useBatcher(fn, options).addItem
|
|
45
|
-
return useCallback((item: TValue) => batchedFn(item), [batchedFn])
|
|
46
|
-
}
|