@ahoo-wang/fetcher-react 2.13.11 → 2.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,6 +27,10 @@ robust data fetching capabilities.
27
27
  - [Installation](#installation)
28
28
  - [Usage](#usage)
29
29
  - [useFetcher Hook](#usefetcher-hook)
30
+ - [Debounced Hooks](#debounced-hooks)
31
+ - [useDebouncedCallback](#usedebouncedcallback)
32
+ - [useDebouncedExecutePromise](#usedebouncedexecutepromise)
33
+ - [useDebouncedFetcher](#usedebouncedfetcher)
30
34
  - [useExecutePromise Hook](#useexecutepromise-hook)
31
35
  - [usePromiseState Hook](#usepromisestate-hook)
32
36
  - [useRequestId Hook](#userequestid-hook)
@@ -125,6 +129,134 @@ const MyComponent = () => {
125
129
  };
126
130
  ```
127
131
 
132
+ ### Debounced Hooks
133
+
134
+ 🚀 **Advanced Debouncing for React Applications** - Powerful hooks that combine debouncing with async operations, providing seamless rate limiting for API calls, user interactions, and promise execution.
135
+
136
+ #### useDebouncedCallback
137
+
138
+ A React hook that provides a debounced version of any callback function with leading/trailing edge execution options.
139
+
140
+ ```typescript jsx
141
+ import { useDebouncedCallback } from '@ahoo-wang/fetcher-react';
142
+
143
+ const SearchComponent = () => {
144
+ const { run: debouncedSearch, cancel, isPending } = useDebouncedCallback(
145
+ async (query: string) => {
146
+ const response = await fetch(`/api/search?q=${query}`);
147
+ const results = await response.json();
148
+ console.log('Search results:', results);
149
+ },
150
+ { delay: 300 }
151
+ );
152
+
153
+ const handleSearch = (query: string) => {
154
+ if (query.trim()) {
155
+ debouncedSearch(query);
156
+ } else {
157
+ cancel(); // Cancel any pending search
158
+ }
159
+ };
160
+
161
+ return (
162
+ <div>
163
+ <input
164
+ type="text"
165
+ placeholder="Search..."
166
+ onChange={(e) => handleSearch(e.target.value)}
167
+ />
168
+ {isPending() && <div>Searching...</div>}
169
+ </div>
170
+ );
171
+ };
172
+ ```
173
+
174
+ **Configuration Options:**
175
+
176
+ - `delay`: Delay in milliseconds before execution (required, positive number)
177
+ - `leading`: Execute immediately on first call (default: false)
178
+ - `trailing`: Execute after delay on last call (default: true)
179
+
180
+ #### useDebouncedExecutePromise
181
+
182
+ Combines promise execution with debouncing functionality, perfect for API calls and async operations.
183
+
184
+ ```typescript jsx
185
+ import { useDebouncedExecutePromise } from '@ahoo-wang/fetcher-react';
186
+
187
+ const DataFetcher = () => {
188
+ const { loading, result, error, run } = useDebouncedExecutePromise({
189
+ debounce: { delay: 300 },
190
+ });
191
+
192
+ const handleLoadUser = (userId: string) => {
193
+ run(async () => {
194
+ const response = await fetch(`/api/users/${userId}`);
195
+ return response.json();
196
+ });
197
+ };
198
+
199
+ return (
200
+ <div>
201
+ <button onClick={() => handleLoadUser('user123')}>
202
+ Load User
203
+ </button>
204
+ {loading && <div>Loading...</div>}
205
+ {error && <div>Error: {error.message}</div>}
206
+ {result && <div>User: {result.name}</div>}
207
+ </div>
208
+ );
209
+ };
210
+ ```
211
+
212
+ #### useDebouncedFetcher
213
+
214
+ Specialized hook combining HTTP fetching with debouncing, built on top of the core fetcher library.
215
+
216
+ ```typescript jsx
217
+ import { useDebouncedFetcher } from '@ahoo-wang/fetcher-react';
218
+
219
+ const SearchInput = () => {
220
+ const [query, setQuery] = useState('');
221
+ const { loading, result, error, run } = useDebouncedFetcher({
222
+ debounce: { delay: 300 },
223
+ onSuccess: (data) => {
224
+ setSearchResults(data.results);
225
+ }
226
+ });
227
+
228
+ const handleChange = (value: string) => {
229
+ setQuery(value);
230
+ if (value.trim()) {
231
+ run({
232
+ url: '/api/search',
233
+ method: 'GET',
234
+ params: { q: value }
235
+ });
236
+ }
237
+ };
238
+
239
+ return (
240
+ <div>
241
+ <input
242
+ value={query}
243
+ onChange={(e) => handleChange(e.target.value)}
244
+ placeholder="Search..."
245
+ />
246
+ {loading && <div>Searching...</div>}
247
+ {error && <div>Error: {error.message}</div>}
248
+ {result && <SearchResults data={result} />}
249
+ </div>
250
+ );
251
+ };
252
+ ```
253
+
254
+ **Debouncing Strategies:**
255
+
256
+ - **Leading Edge**: Execute immediately on first call, then debounce subsequent calls
257
+ - **Trailing Edge**: Execute after delay on last call (default behavior)
258
+ - **Leading + Trailing**: Execute immediately, then again after delay if called again
259
+
128
260
  ### useExecutePromise Hook
129
261
 
130
262
  The `useExecutePromise` hook manages asynchronous operations with automatic state handling, built-in race condition
@@ -1259,6 +1391,107 @@ describe('useListQuery', () => {
1259
1391
 
1260
1392
  ## API Reference
1261
1393
 
1394
+ ### Debounced Hooks
1395
+
1396
+ #### useDebouncedCallback
1397
+
1398
+ ```typescript
1399
+ function useDebouncedCallback<T extends (...args: any[]) => any>(
1400
+ callback: T,
1401
+ options: UseDebouncedCallbackOptions,
1402
+ ): UseDebouncedCallbackReturn<T>;
1403
+ ```
1404
+
1405
+ A React hook that provides a debounced version of a callback function with leading/trailing edge execution options.
1406
+
1407
+ **Type Parameters:**
1408
+
1409
+ - `T`: The type of the callback function
1410
+
1411
+ **Parameters:**
1412
+
1413
+ - `callback`: The function to debounce
1414
+ - `options`: Configuration object
1415
+ - `delay`: Delay in milliseconds before execution (required, positive number)
1416
+ - `leading?`: Execute immediately on first call (default: false)
1417
+ - `trailing?`: Execute after delay on last call (default: true)
1418
+
1419
+ **Returns:**
1420
+
1421
+ An object containing:
1422
+
1423
+ - `run`: Function to execute the debounced callback with arguments
1424
+ - `cancel`: Function to cancel any pending debounced execution
1425
+ - `isPending`: Function that returns true if a debounced execution is currently pending
1426
+
1427
+ #### useDebouncedExecutePromise
1428
+
1429
+ ```typescript
1430
+ function useDebouncedExecutePromise<R = unknown, E = FetcherError>(
1431
+ options: UseDebouncedExecutePromiseOptions<R, E>,
1432
+ ): UseDebouncedExecutePromiseReturn<R, E>;
1433
+ ```
1434
+
1435
+ Combines promise execution with debouncing functionality.
1436
+
1437
+ **Type Parameters:**
1438
+
1439
+ - `R`: The type of the promise result (defaults to unknown)
1440
+ - `E`: The type of the error (defaults to FetcherError)
1441
+
1442
+ **Parameters:**
1443
+
1444
+ - `options`: Configuration object containing promise execution options and debounce settings
1445
+ - `debounce`: Debounce configuration (delay, leading, trailing)
1446
+ - All options from `UseExecutePromiseOptions`
1447
+
1448
+ **Returns:**
1449
+
1450
+ An object containing:
1451
+
1452
+ - `loading`: Boolean indicating if the promise is currently executing
1453
+ - `result`: The resolved value of the promise
1454
+ - `error`: Any error that occurred during execution
1455
+ - `status`: Current execution status
1456
+ - `run`: Debounced function to execute the promise with provided arguments
1457
+ - `cancel`: Function to cancel any pending debounced execution
1458
+ - `isPending`: Boolean indicating if a debounced call is pending
1459
+ - `reset`: Function to reset the hook state to initial values
1460
+
1461
+ #### useDebouncedFetcher
1462
+
1463
+ ```typescript
1464
+ function useDebouncedFetcher<R, E = FetcherError>(
1465
+ options: UseDebouncedFetcherOptions<R, E>,
1466
+ ): UseDebouncedFetcherReturn<R, E>;
1467
+ ```
1468
+
1469
+ Specialized hook combining HTTP fetching with debouncing.
1470
+
1471
+ **Type Parameters:**
1472
+
1473
+ - `R`: The type of the fetch result
1474
+ - `E`: The type of the error (defaults to FetcherError)
1475
+
1476
+ **Parameters:**
1477
+
1478
+ - `options`: Configuration object extending `UseFetcherOptions` and `DebounceCapable`
1479
+ - HTTP request options (method, headers, timeout, etc.)
1480
+ - `debounce`: Debounce configuration (delay, leading, trailing)
1481
+
1482
+ **Returns:**
1483
+
1484
+ An object containing:
1485
+
1486
+ - `loading`: Boolean indicating if the fetch is currently executing
1487
+ - `result`: The resolved value of the fetch
1488
+ - `error`: Any error that occurred during execution
1489
+ - `status`: Current execution status
1490
+ - `exchange`: The FetchExchange object representing the ongoing fetch operation
1491
+ - `run`: Function to execute the debounced fetch with request parameters
1492
+ - `cancel`: Function to cancel any pending debounced execution
1493
+ - `isPending`: Boolean indicating if a debounced call is pending
1494
+
1262
1495
  ### useFetcher
1263
1496
 
1264
1497
  ```typescript
package/README.zh-CN.md CHANGED
@@ -26,6 +26,10 @@
26
26
  - [快速开始](#快速开始)
27
27
  - [使用方法](#使用方法)
28
28
  - [useFetcher Hook](#usefetcher-hook)
29
+ - [防抖 Hooks](#防抖-hooks)
30
+ - [useDebouncedCallback](#usedebouncedcallback)
31
+ - [useDebouncedExecutePromise](#usedebouncedexecutepromise)
32
+ - [useDebouncedFetcher](#usedebouncedfetcher)
29
33
  - [useExecutePromise Hook](#useexecutepromise-hook)
30
34
  - [usePromiseState Hook](#usepromisestate-hook)
31
35
  - [useRequestId Hook](#userequestid-hook)
@@ -123,6 +127,134 @@ const MyComponent = () => {
123
127
  };
124
128
  ```
125
129
 
130
+ ### 防抖 Hooks
131
+
132
+ 🚀 **高级 React 防抖库** - 强大的 hooks 将防抖与异步操作相结合,为 API 调用、用户交互和 Promise 执行提供无缝的速率限制。
133
+
134
+ #### useDebouncedCallback
135
+
136
+ 一个 React hook,为任何回调函数提供防抖版本,支持前缘/后缘执行选项。
137
+
138
+ ```typescript jsx
139
+ import { useDebouncedCallback } from '@ahoo-wang/fetcher-react';
140
+
141
+ const SearchComponent = () => {
142
+ const { run: debouncedSearch, cancel, isPending } = useDebouncedCallback(
143
+ async (query: string) => {
144
+ const response = await fetch(`/api/search?q=${query}`);
145
+ const results = await response.json();
146
+ console.log('搜索结果:', results);
147
+ },
148
+ { delay: 300 }
149
+ );
150
+
151
+ const handleSearch = (query: string) => {
152
+ if (query.trim()) {
153
+ debouncedSearch(query);
154
+ } else {
155
+ cancel(); // 取消任何待处理的搜索
156
+ }
157
+ };
158
+
159
+ return (
160
+ <div>
161
+ <input
162
+ type="text"
163
+ placeholder="搜索..."
164
+ onChange={(e) => handleSearch(e.target.value)}
165
+ />
166
+ {isPending() && <div>搜索中...</div>}
167
+ </div>
168
+ );
169
+ };
170
+ ```
171
+
172
+ **配置选项:**
173
+
174
+ - `delay`: 执行前的延迟毫秒数(必需,正数)
175
+ - `leading`: 第一次调用时立即执行(默认: false)
176
+ - `trailing`: 最后一次调用后延迟执行(默认: true)
177
+
178
+ #### useDebouncedExecutePromise
179
+
180
+ 将 Promise 执行与防抖功能相结合,非常适合 API 调用和异步操作。
181
+
182
+ ```typescript jsx
183
+ import { useDebouncedExecutePromise } from '@ahoo-wang/fetcher-react';
184
+
185
+ const DataFetcher = () => {
186
+ const { loading, result, error, run } = useDebouncedExecutePromise({
187
+ debounce: { delay: 300 },
188
+ });
189
+
190
+ const handleLoadUser = (userId: string) => {
191
+ run(async () => {
192
+ const response = await fetch(`/api/users/${userId}`);
193
+ return response.json();
194
+ });
195
+ };
196
+
197
+ return (
198
+ <div>
199
+ <button onClick={() => handleLoadUser('user123')}>
200
+ 加载用户
201
+ </button>
202
+ {loading && <div>加载中...</div>}
203
+ {error && <div>错误: {error.message}</div>}
204
+ {result && <div>用户: {result.name}</div>}
205
+ </div>
206
+ );
207
+ };
208
+ ```
209
+
210
+ #### useDebouncedFetcher
211
+
212
+ 专门的 hook,将 HTTP 获取与防抖相结合,建立在核心获取器库之上。
213
+
214
+ ```typescript jsx
215
+ import { useDebouncedFetcher } from '@ahoo-wang/fetcher-react';
216
+
217
+ const SearchInput = () => {
218
+ const [query, setQuery] = useState('');
219
+ const { loading, result, error, run } = useDebouncedFetcher({
220
+ debounce: { delay: 300 },
221
+ onSuccess: (data) => {
222
+ setSearchResults(data.results);
223
+ }
224
+ });
225
+
226
+ const handleChange = (value: string) => {
227
+ setQuery(value);
228
+ if (value.trim()) {
229
+ run({
230
+ url: '/api/search',
231
+ method: 'GET',
232
+ params: { q: value }
233
+ });
234
+ }
235
+ };
236
+
237
+ return (
238
+ <div>
239
+ <input
240
+ value={query}
241
+ onChange={(e) => handleChange(e.target.value)}
242
+ placeholder="搜索..."
243
+ />
244
+ {loading && <div>搜索中...</div>}
245
+ {error && <div>错误: {error.message}</div>}
246
+ {result && <SearchResults data={result} />}
247
+ </div>
248
+ );
249
+ };
250
+ ```
251
+
252
+ **防抖策略:**
253
+
254
+ - **前缘执行**: 第一次调用时立即执行,然后对后续调用进行防抖
255
+ - **后缘执行**: 最后一次调用后延迟执行(默认行为)
256
+ - **前缘 + 后缘**: 立即执行,如果再次调用则在延迟后再次执行
257
+
126
258
  ### useExecutePromise Hook
127
259
 
128
260
  `useExecutePromise` hook 管理异步操作,具有自动状态处理、竞态条件保护和 promise 状态选项支持。
@@ -632,6 +764,107 @@ const MyComponent = () => {
632
764
 
633
765
  ## API 参考
634
766
 
767
+ ### 防抖 Hooks
768
+
769
+ #### useDebouncedCallback
770
+
771
+ ```typescript
772
+ function useDebouncedCallback<T extends (...args: any[]) => any>(
773
+ callback: T,
774
+ options: UseDebouncedCallbackOptions,
775
+ ): UseDebouncedCallbackReturn<T>;
776
+ ```
777
+
778
+ 一个 React hook,为回调函数提供防抖版本,支持前缘/后缘执行选项。
779
+
780
+ **类型参数:**
781
+
782
+ - `T`: 回调函数的类型
783
+
784
+ **参数:**
785
+
786
+ - `callback`: 要防抖的函数
787
+ - `options`: 配置对象
788
+ - `delay`: 执行前的延迟毫秒数(必需,正数)
789
+ - `leading?`: 第一次调用时立即执行(默认: false)
790
+ - `trailing?`: 最后一次调用后延迟执行(默认: true)
791
+
792
+ **返回:**
793
+
794
+ 包含以下内容的对象:
795
+
796
+ - `run`: 使用参数执行防抖回调的函数
797
+ - `cancel`: 取消任何待处理防抖执行的函数
798
+ - `isPending`: 返回布尔值表示防抖执行当前是否待处理的函数
799
+
800
+ #### useDebouncedExecutePromise
801
+
802
+ ```typescript
803
+ function useDebouncedExecutePromise<R = unknown, E = FetcherError>(
804
+ options: UseDebouncedExecutePromiseOptions<R, E>,
805
+ ): UseDebouncedExecutePromiseReturn<R, E>;
806
+ ```
807
+
808
+ 将 Promise 执行与防抖功能相结合。
809
+
810
+ **类型参数:**
811
+
812
+ - `R`: Promise 结果的类型(默认为 unknown)
813
+ - `E`: 错误的类型(默认为 FetcherError)
814
+
815
+ **参数:**
816
+
817
+ - `options`: 包含 Promise 执行选项和防抖设置的配置对象
818
+ - `debounce`: 防抖配置(delay、leading、trailing)
819
+ - `UseExecutePromiseOptions` 的所有选项
820
+
821
+ **返回:**
822
+
823
+ 包含以下内容的对象:
824
+
825
+ - `loading`: 布尔值,表示 Promise 当前是否正在执行
826
+ - `result`: Promise 的解析值
827
+ - `error`: 执行期间发生的任何错误
828
+ - `status`: 当前执行状态
829
+ - `run`: 使用提供的参数执行防抖 Promise 的函数
830
+ - `cancel`: 取消任何待处理防抖执行的函数
831
+ - `isPending`: 布尔值,表示防抖调用是否待处理
832
+ - `reset`: 将 hook 状态重置为初始值的函数
833
+
834
+ #### useDebouncedFetcher
835
+
836
+ ```typescript
837
+ function useDebouncedFetcher<R, E = FetcherError>(
838
+ options: UseDebouncedFetcherOptions<R, E>,
839
+ ): UseDebouncedFetcherReturn<R, E>;
840
+ ```
841
+
842
+ 专门的 hook,将 HTTP 获取与防抖相结合。
843
+
844
+ **类型参数:**
845
+
846
+ - `R`: 获取结果的类型
847
+ - `E`: 错误的类型(默认为 FetcherError)
848
+
849
+ **参数:**
850
+
851
+ - `options`: 扩展 `UseFetcherOptions` 和 `DebounceCapable` 的配置对象
852
+ - HTTP 请求选项(method、headers、timeout 等)
853
+ - `debounce`: 防抖配置(delay、leading、trailing)
854
+
855
+ **返回:**
856
+
857
+ 包含以下内容的对象:
858
+
859
+ - `loading`: 布尔值,表示获取当前是否正在执行
860
+ - `result`: 获取的解析值
861
+ - `error`: 执行期间发生的任何错误
862
+ - `status`: 当前执行状态
863
+ - `exchange`: 表示正在进行的获取操作的 FetchExchange 对象
864
+ - `run`: 使用请求参数执行防抖获取的函数
865
+ - `cancel`: 取消任何待处理防抖执行的函数
866
+ - `isPending`: 布尔值,表示防抖调用是否待处理
867
+
635
868
  ### useFetcher
636
869
 
637
870
  ```typescript
@@ -4,4 +4,6 @@ export * from './useRequestId';
4
4
  export * from './useLatest';
5
5
  export * from './useMounted';
6
6
  export * from './useRefs';
7
+ export * from './useDebouncedCallback';
8
+ export * from './useDebouncedExecutePromise';
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC;AAC1B,cAAc,wBAAwB,CAAC;AACvC,cAAc,8BAA8B,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Options for configuring the debounced callback behavior.
3
+ */
4
+ export interface UseDebouncedCallbackOptions {
5
+ /** The delay in milliseconds before the callback is invoked. Must be a positive number. */
6
+ delay: number;
7
+ /** Whether to invoke the callback immediately on the leading edge of the timeout. Defaults to false. */
8
+ leading?: boolean;
9
+ /** Whether to invoke the callback on the trailing edge of the timeout. Defaults to true. */
10
+ trailing?: boolean;
11
+ }
12
+ /**
13
+ * Return type of the useDebouncedCallback hook.
14
+ * @template T - The type of the original callback function.
15
+ */
16
+ export interface UseDebouncedCallbackReturn<T extends (...args: any[]) => any> {
17
+ /** Function to execute the debounced callback with the provided arguments. */
18
+ readonly run: (...args: Parameters<T>) => void;
19
+ /** Function to cancel any pending debounced execution. */
20
+ readonly cancel: () => void;
21
+ /** Function to check if a debounced execution is currently pending. */
22
+ readonly isPending: () => boolean;
23
+ }
24
+ /**
25
+ * A React hook that provides a debounced version of a callback function.
26
+ * The callback will be invoked after a specified delay, with options for leading and trailing edge execution.
27
+ * This is useful for optimizing performance in scenarios like search input handling or window resizing.
28
+ *
29
+ * @template T - The type of the callback function.
30
+ * @param callback - The function to debounce. It can accept any number of arguments.
31
+ * @param options - Configuration object for debouncing behavior.
32
+ * @param options.delay - The delay in milliseconds before the callback is invoked. Must be a positive number.
33
+ * @param options.leading - If true, the callback is invoked immediately on the first call, then debounced. Defaults to false.
34
+ * @param options.trailing - If true, the callback is invoked after the delay on the last call. Defaults to true.
35
+ * @returns An object containing:
36
+ * - `run`: Function to execute the debounced callback with arguments.
37
+ * - `cancel`: Function to cancel any pending debounced execution.
38
+ * - `isPending`: Function that returns true if a debounced execution is currently pending.
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * const { run, cancel } = useDebouncedCallback(
43
+ * (query: string) => {
44
+ * console.log('Searching for:', query);
45
+ * // Perform search API call
46
+ * },
47
+ * { delay: 300 }
48
+ * );
49
+ *
50
+ * // Call the debounced function
51
+ * run('search term');
52
+ *
53
+ * // Cancel if needed
54
+ * cancel();
55
+ * ```
56
+ *
57
+ * @example With leading edge execution:
58
+ * ```typescript
59
+ * const { run } = useDebouncedCallback(
60
+ * () => console.log('Immediate and debounced'),
61
+ * { delay: 500, leading: true, trailing: true }
62
+ * );
63
+ *
64
+ * run(); // Logs immediately, then again after 500ms if called again
65
+ * ```
66
+ *
67
+ * @throws {Error} Throws an error if both `leading` and `trailing` options are set to false, as at least one must be true for the debounce to function.
68
+ * @throws Exceptions from the callback function itself should be handled by the caller.
69
+ */
70
+ export declare function useDebouncedCallback<T extends (...args: any[]) => any>(callback: T, options: UseDebouncedCallbackOptions): UseDebouncedCallbackReturn<T>;
71
+ //# sourceMappingURL=useDebouncedCallback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDebouncedCallback.d.ts","sourceRoot":"","sources":["../../src/core/useDebouncedCallback.ts"],"names":[],"mappings":"AAeA;;GAEG;AACH,MAAM,WAAW,2BAA2B;IAC1C,2FAA2F;IAC3F,KAAK,EAAE,MAAM,CAAC;IACd,wGAAwG;IACxG,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,4FAA4F;IAC5F,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;GAGG;AACH,MAAM,WAAW,0BAA0B,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG;IAC3E,8EAA8E;IAC9E,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;IAC/C,0DAA0D;IAC1D,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC;IAC5B,uEAAuE;IACvE,QAAQ,CAAC,SAAS,EAAE,MAAM,OAAO,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EACpE,QAAQ,EAAE,CAAC,EACX,OAAO,EAAE,2BAA2B,GACnC,0BAA0B,CAAC,CAAC,CAAC,CAwE/B"}
@@ -0,0 +1,92 @@
1
+ import { UseExecutePromiseOptions, UseExecutePromiseReturn } from './useExecutePromise';
2
+ import { UseDebouncedCallbackOptions, UseDebouncedCallbackReturn } from './useDebouncedCallback';
3
+ import { FetcherError } from '@ahoo-wang/fetcher';
4
+ /**
5
+ * Interface for objects that support debouncing configuration.
6
+ * This interface defines the structure for debounce settings that can be applied
7
+ * to promise execution to control the timing and behavior of debounced calls.
8
+ */
9
+ export interface DebounceCapable {
10
+ /**
11
+ * Debounce options for execute calls, including delay and leading/trailing behavior.
12
+ * Specifies how the debouncing should work, such as the delay duration and whether
13
+ * to execute on the leading edge, trailing edge, or both.
14
+ */
15
+ debounce: UseDebouncedCallbackOptions;
16
+ }
17
+ /**
18
+ * Options for configuring the useDebouncedExecutePromise hook.
19
+ * Combines promise execution options with debouncing capabilities to provide
20
+ * fine-grained control over asynchronous operations with rate limiting.
21
+ *
22
+ * @template R - The type of the promise result
23
+ * @template E - The type of the error (defaults to unknown)
24
+ */
25
+ export interface UseDebouncedExecutePromiseOptions<R, E = unknown> extends UseExecutePromiseOptions<R, E>, DebounceCapable {
26
+ }
27
+ /**
28
+ * Return type for the useDebouncedExecutePromise hook.
29
+ * Provides access to the promise execution state and debounced execution controls,
30
+ * allowing components to trigger debounced promises and monitor their progress.
31
+ *
32
+ * @template R - The type of the promise result
33
+ * @template E - The type of the error (defaults to unknown)
34
+ */
35
+ export interface UseDebouncedExecutePromiseReturn<R, E = unknown> extends Omit<UseExecutePromiseReturn<R, E>, 'execute'>, UseDebouncedCallbackReturn<UseExecutePromiseReturn<R, E>['execute']> {
36
+ }
37
+ /**
38
+ * A React hook that combines promise execution with debouncing functionality.
39
+ * This hook prevents excessive API calls by debouncing the execution of promises,
40
+ * which is particularly useful for scenarios like search inputs, form submissions,
41
+ * or any rapid user interactions that trigger asynchronous operations.
42
+ *
43
+ * The hook integrates the useExecutePromise hook for promise management with
44
+ * useDebouncedCallback for rate limiting, providing a seamless way to handle
45
+ * debounced asynchronous operations in React components.
46
+ *
47
+ * @template R - The type of the promise result (defaults to unknown)
48
+ * @template E - The type of the error (defaults to FetcherError)
49
+ * @param options - Configuration object containing:
50
+ * - All options from UseExecutePromiseOptions (promise execution settings)
51
+ * - debounce: Debounce configuration including delay, leading/trailing behavior
52
+ * @returns An object containing:
53
+ * - loading: Boolean indicating if the promise is currently executing
54
+ * - result: The resolved value of the promise (R)
55
+ * - error: Any error that occurred during execution (E)
56
+ * - status: Current execution status ('idle' | 'pending' | 'fulfilled' | 'rejected')
57
+ * - run: Debounced function to execute the promise with provided arguments
58
+ * - cancel: Function to cancel any pending debounced execution
59
+ * - isPending: Boolean indicating if a debounced call is pending
60
+ * - reset: Function to reset the hook state to initial values
61
+ * @throws {FetcherError} When the underlying promise execution fails and no custom error handler is provided
62
+ * @throws {Error} When invalid options are provided or debounce configuration is malformed
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * import { useDebouncedExecutePromise } from '@ahoo-wang/fetcher-react';
67
+ *
68
+ * function SearchComponent() {
69
+ * const { loading, result, error, run } = useDebouncedExecutePromise({
70
+ * debounce: { delay: 300 },
71
+ * });
72
+ *
73
+ * const handleSearch = (query: string) => {
74
+ * run(async () => {
75
+ * const response = await fetch(`/api/search?q=${query}`);
76
+ * return response.json();
77
+ * });
78
+ * };
79
+ *
80
+ * return (
81
+ * <div>
82
+ * <input onChange={(e) => handleSearch(e.target.value)} />
83
+ * {loading && <p>Searching...</p>}
84
+ * {result && <ul>{result.map(item => <li key={item.id}>{item.name}</li>)}</ul>}
85
+ * {error && <p>Error: {error.message}</p>}
86
+ * </div>
87
+ * );
88
+ * }
89
+ * ```
90
+ */
91
+ export declare function useDebouncedExecutePromise<R = unknown, E = FetcherError>(options: UseDebouncedExecutePromiseOptions<R, E>): UseDebouncedExecutePromiseReturn<R, E>;
92
+ //# sourceMappingURL=useDebouncedExecutePromise.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useDebouncedExecutePromise.d.ts","sourceRoot":"","sources":["../../src/core/useDebouncedExecutePromise.ts"],"names":[],"mappings":"AAaA,OAAO,EAEL,wBAAwB,EACxB,uBAAuB,EACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,2BAA2B,EAC3B,0BAA0B,EAC3B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGlD;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;OAIG;IACH,QAAQ,EAAE,2BAA2B,CAAC;CACvC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,iCAAiC,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAC/D,SAAQ,wBAAwB,CAAC,CAAC,EAAE,CAAC,CAAC,EACpC,eAAe;CAAG;AAEtB;;;;;;;GAOG;AACH,MAAM,WAAW,gCAAgC,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAC9D,SAAQ,IAAI,CAAC,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,SAAS,CAAC,EACpD,0BAA0B,CAAC,uBAAuB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;CAAG;AAE3E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,YAAY,EACtE,OAAO,EAAE,iCAAiC,CAAC,CAAC,EAAE,CAAC,CAAC,GAC/C,gCAAgC,CAAC,CAAC,EAAE,CAAC,CAAC,CAqBxC"}