@ahoo-wang/fetcher-react 2.13.10 → 2.15.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 +232 -0
- package/README.zh-CN.md +232 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/useDebouncedCallback.d.ts +71 -0
- package/dist/core/useDebouncedCallback.d.ts.map +1 -0
- package/dist/core/useDebouncedExecutePromise.d.ts +93 -0
- package/dist/core/useDebouncedExecutePromise.d.ts.map +1 -0
- package/dist/core/useExecutePromise.d.ts +55 -17
- package/dist/core/useExecutePromise.d.ts.map +1 -1
- package/dist/fetcher/index.d.ts +1 -0
- package/dist/fetcher/index.d.ts.map +1 -1
- package/dist/fetcher/useDebouncedFetcher.d.ts +92 -0
- package/dist/fetcher/useDebouncedFetcher.d.ts.map +1 -0
- package/dist/fetcher/useFetcher.d.ts +103 -18
- package/dist/fetcher/useFetcher.d.ts.map +1 -1
- package/dist/index.es.js +291 -186
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +1 -1
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,133 @@ 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
|
+
promise: async (userId: string) => {
|
|
190
|
+
const response = await fetch(`/api/users/${userId}`);
|
|
191
|
+
return response.json();
|
|
192
|
+
},
|
|
193
|
+
debounce: { delay: 300 },
|
|
194
|
+
onSuccess: (user) => console.log('User loaded:', user),
|
|
195
|
+
onError: (error) => console.error('Failed to load user:', error),
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
return (
|
|
199
|
+
<div>
|
|
200
|
+
<button onClick={() => run('user123')}>
|
|
201
|
+
Load User
|
|
202
|
+
</button>
|
|
203
|
+
{loading && <div>Loading...</div>}
|
|
204
|
+
{error && <div>Error: {error.message}</div>}
|
|
205
|
+
{result && <div>User: {result.name}</div>}
|
|
206
|
+
</div>
|
|
207
|
+
);
|
|
208
|
+
};
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
#### useDebouncedFetcher
|
|
212
|
+
|
|
213
|
+
Specialized hook combining HTTP fetching with debouncing, built on top of the core fetcher library.
|
|
214
|
+
|
|
215
|
+
```typescript jsx
|
|
216
|
+
import { useDebouncedFetcher } from '@ahoo-wang/fetcher-react';
|
|
217
|
+
|
|
218
|
+
const SearchInput = () => {
|
|
219
|
+
const [query, setQuery] = useState('');
|
|
220
|
+
const { loading, result, error, run } = useDebouncedFetcher({
|
|
221
|
+
debounce: { delay: 300 },
|
|
222
|
+
onSuccess: (data) => {
|
|
223
|
+
setSearchResults(data.results);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
const handleChange = (value: string) => {
|
|
228
|
+
setQuery(value);
|
|
229
|
+
if (value.trim()) {
|
|
230
|
+
run({
|
|
231
|
+
url: '/api/search',
|
|
232
|
+
method: 'GET',
|
|
233
|
+
params: { q: value }
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
return (
|
|
239
|
+
<div>
|
|
240
|
+
<input
|
|
241
|
+
value={query}
|
|
242
|
+
onChange={(e) => handleChange(e.target.value)}
|
|
243
|
+
placeholder="Search..."
|
|
244
|
+
/>
|
|
245
|
+
{loading && <div>Searching...</div>}
|
|
246
|
+
{error && <div>Error: {error.message}</div>}
|
|
247
|
+
{result && <SearchResults data={result} />}
|
|
248
|
+
</div>
|
|
249
|
+
);
|
|
250
|
+
};
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
**Debouncing Strategies:**
|
|
254
|
+
|
|
255
|
+
- **Leading Edge**: Execute immediately on first call, then debounce subsequent calls
|
|
256
|
+
- **Trailing Edge**: Execute after delay on last call (default behavior)
|
|
257
|
+
- **Leading + Trailing**: Execute immediately, then again after delay if called again
|
|
258
|
+
|
|
128
259
|
### useExecutePromise Hook
|
|
129
260
|
|
|
130
261
|
The `useExecutePromise` hook manages asynchronous operations with automatic state handling, built-in race condition
|
|
@@ -1259,6 +1390,107 @@ describe('useListQuery', () => {
|
|
|
1259
1390
|
|
|
1260
1391
|
## API Reference
|
|
1261
1392
|
|
|
1393
|
+
### Debounced Hooks
|
|
1394
|
+
|
|
1395
|
+
#### useDebouncedCallback
|
|
1396
|
+
|
|
1397
|
+
```typescript
|
|
1398
|
+
function useDebouncedCallback<T extends (...args: any[]) => any>(
|
|
1399
|
+
callback: T,
|
|
1400
|
+
options: UseDebouncedCallbackOptions,
|
|
1401
|
+
): UseDebouncedCallbackReturn<T>;
|
|
1402
|
+
```
|
|
1403
|
+
|
|
1404
|
+
A React hook that provides a debounced version of a callback function with leading/trailing edge execution options.
|
|
1405
|
+
|
|
1406
|
+
**Type Parameters:**
|
|
1407
|
+
|
|
1408
|
+
- `T`: The type of the callback function
|
|
1409
|
+
|
|
1410
|
+
**Parameters:**
|
|
1411
|
+
|
|
1412
|
+
- `callback`: The function to debounce
|
|
1413
|
+
- `options`: Configuration object
|
|
1414
|
+
- `delay`: Delay in milliseconds before execution (required, positive number)
|
|
1415
|
+
- `leading?`: Execute immediately on first call (default: false)
|
|
1416
|
+
- `trailing?`: Execute after delay on last call (default: true)
|
|
1417
|
+
|
|
1418
|
+
**Returns:**
|
|
1419
|
+
|
|
1420
|
+
An object containing:
|
|
1421
|
+
|
|
1422
|
+
- `run`: Function to execute the debounced callback with arguments
|
|
1423
|
+
- `cancel`: Function to cancel any pending debounced execution
|
|
1424
|
+
- `isPending`: Function that returns true if a debounced execution is currently pending
|
|
1425
|
+
|
|
1426
|
+
#### useDebouncedExecutePromise
|
|
1427
|
+
|
|
1428
|
+
```typescript
|
|
1429
|
+
function useDebouncedExecutePromise<R = unknown, E = FetcherError>(
|
|
1430
|
+
options: UseDebouncedExecutePromiseOptions<R, E>,
|
|
1431
|
+
): UseDebouncedExecutePromiseReturn<R, E>;
|
|
1432
|
+
```
|
|
1433
|
+
|
|
1434
|
+
Combines promise execution with debouncing functionality.
|
|
1435
|
+
|
|
1436
|
+
**Type Parameters:**
|
|
1437
|
+
|
|
1438
|
+
- `R`: The type of the promise result (defaults to unknown)
|
|
1439
|
+
- `E`: The type of the error (defaults to FetcherError)
|
|
1440
|
+
|
|
1441
|
+
**Parameters:**
|
|
1442
|
+
|
|
1443
|
+
- `options`: Configuration object containing promise execution options and debounce settings
|
|
1444
|
+
- `debounce`: Debounce configuration (delay, leading, trailing)
|
|
1445
|
+
- All options from `UseExecutePromiseOptions`
|
|
1446
|
+
|
|
1447
|
+
**Returns:**
|
|
1448
|
+
|
|
1449
|
+
An object containing:
|
|
1450
|
+
|
|
1451
|
+
- `loading`: Boolean indicating if the promise is currently executing
|
|
1452
|
+
- `result`: The resolved value of the promise
|
|
1453
|
+
- `error`: Any error that occurred during execution
|
|
1454
|
+
- `status`: Current execution status
|
|
1455
|
+
- `run`: Debounced function to execute the promise with provided arguments
|
|
1456
|
+
- `cancel`: Function to cancel any pending debounced execution
|
|
1457
|
+
- `isPending`: Boolean indicating if a debounced call is pending
|
|
1458
|
+
- `reset`: Function to reset the hook state to initial values
|
|
1459
|
+
|
|
1460
|
+
#### useDebouncedFetcher
|
|
1461
|
+
|
|
1462
|
+
```typescript
|
|
1463
|
+
function useDebouncedFetcher<R, E = FetcherError>(
|
|
1464
|
+
options: UseDebouncedFetcherOptions<R, E>,
|
|
1465
|
+
): UseDebouncedFetcherReturn<R, E>;
|
|
1466
|
+
```
|
|
1467
|
+
|
|
1468
|
+
Specialized hook combining HTTP fetching with debouncing.
|
|
1469
|
+
|
|
1470
|
+
**Type Parameters:**
|
|
1471
|
+
|
|
1472
|
+
- `R`: The type of the fetch result
|
|
1473
|
+
- `E`: The type of the error (defaults to FetcherError)
|
|
1474
|
+
|
|
1475
|
+
**Parameters:**
|
|
1476
|
+
|
|
1477
|
+
- `options`: Configuration object extending `UseFetcherOptions` and `DebounceCapable`
|
|
1478
|
+
- HTTP request options (method, headers, timeout, etc.)
|
|
1479
|
+
- `debounce`: Debounce configuration (delay, leading, trailing)
|
|
1480
|
+
|
|
1481
|
+
**Returns:**
|
|
1482
|
+
|
|
1483
|
+
An object containing:
|
|
1484
|
+
|
|
1485
|
+
- `loading`: Boolean indicating if the fetch is currently executing
|
|
1486
|
+
- `result`: The resolved value of the fetch
|
|
1487
|
+
- `error`: Any error that occurred during execution
|
|
1488
|
+
- `status`: Current execution status
|
|
1489
|
+
- `exchange`: The FetchExchange object representing the ongoing fetch operation
|
|
1490
|
+
- `run`: Function to execute the debounced fetch with request parameters
|
|
1491
|
+
- `cancel`: Function to cancel any pending debounced execution
|
|
1492
|
+
- `isPending`: Boolean indicating if a debounced call is pending
|
|
1493
|
+
|
|
1262
1494
|
### useFetcher
|
|
1263
1495
|
|
|
1264
1496
|
```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,133 @@ 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
|
+
promise: async (userId: string) => {
|
|
188
|
+
const response = await fetch(`/api/users/${userId}`);
|
|
189
|
+
return response.json();
|
|
190
|
+
},
|
|
191
|
+
debounce: { delay: 300 },
|
|
192
|
+
onSuccess: (user) => console.log('用户加载:', user),
|
|
193
|
+
onError: (error) => console.error('加载用户失败:', error),
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
return (
|
|
197
|
+
<div>
|
|
198
|
+
<button onClick={() => run('user123')}>
|
|
199
|
+
加载用户
|
|
200
|
+
</button>
|
|
201
|
+
{loading && <div>加载中...</div>}
|
|
202
|
+
{error && <div>错误: {error.message}</div>}
|
|
203
|
+
{result && <div>用户: {result.name}</div>}
|
|
204
|
+
</div>
|
|
205
|
+
);
|
|
206
|
+
};
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
#### useDebouncedFetcher
|
|
210
|
+
|
|
211
|
+
专门的 hook,将 HTTP 获取与防抖相结合,建立在核心获取器库之上。
|
|
212
|
+
|
|
213
|
+
```typescript jsx
|
|
214
|
+
import { useDebouncedFetcher } from '@ahoo-wang/fetcher-react';
|
|
215
|
+
|
|
216
|
+
const SearchInput = () => {
|
|
217
|
+
const [query, setQuery] = useState('');
|
|
218
|
+
const { loading, result, error, run } = useDebouncedFetcher({
|
|
219
|
+
debounce: { delay: 300 },
|
|
220
|
+
onSuccess: (data) => {
|
|
221
|
+
setSearchResults(data.results);
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
const handleChange = (value: string) => {
|
|
226
|
+
setQuery(value);
|
|
227
|
+
if (value.trim()) {
|
|
228
|
+
run({
|
|
229
|
+
url: '/api/search',
|
|
230
|
+
method: 'GET',
|
|
231
|
+
params: { q: value }
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
return (
|
|
237
|
+
<div>
|
|
238
|
+
<input
|
|
239
|
+
value={query}
|
|
240
|
+
onChange={(e) => handleChange(e.target.value)}
|
|
241
|
+
placeholder="搜索..."
|
|
242
|
+
/>
|
|
243
|
+
{loading && <div>搜索中...</div>}
|
|
244
|
+
{error && <div>错误: {error.message}</div>}
|
|
245
|
+
{result && <SearchResults data={result} />}
|
|
246
|
+
</div>
|
|
247
|
+
);
|
|
248
|
+
};
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
**防抖策略:**
|
|
252
|
+
|
|
253
|
+
- **前缘执行**: 第一次调用时立即执行,然后对后续调用进行防抖
|
|
254
|
+
- **后缘执行**: 最后一次调用后延迟执行(默认行为)
|
|
255
|
+
- **前缘 + 后缘**: 立即执行,如果再次调用则在延迟后再次执行
|
|
256
|
+
|
|
126
257
|
### useExecutePromise Hook
|
|
127
258
|
|
|
128
259
|
`useExecutePromise` hook 管理异步操作,具有自动状态处理、竞态条件保护和 promise 状态选项支持。
|
|
@@ -632,6 +763,107 @@ const MyComponent = () => {
|
|
|
632
763
|
|
|
633
764
|
## API 参考
|
|
634
765
|
|
|
766
|
+
### 防抖 Hooks
|
|
767
|
+
|
|
768
|
+
#### useDebouncedCallback
|
|
769
|
+
|
|
770
|
+
```typescript
|
|
771
|
+
function useDebouncedCallback<T extends (...args: any[]) => any>(
|
|
772
|
+
callback: T,
|
|
773
|
+
options: UseDebouncedCallbackOptions,
|
|
774
|
+
): UseDebouncedCallbackReturn<T>;
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
一个 React hook,为回调函数提供防抖版本,支持前缘/后缘执行选项。
|
|
778
|
+
|
|
779
|
+
**类型参数:**
|
|
780
|
+
|
|
781
|
+
- `T`: 回调函数的类型
|
|
782
|
+
|
|
783
|
+
**参数:**
|
|
784
|
+
|
|
785
|
+
- `callback`: 要防抖的函数
|
|
786
|
+
- `options`: 配置对象
|
|
787
|
+
- `delay`: 执行前的延迟毫秒数(必需,正数)
|
|
788
|
+
- `leading?`: 第一次调用时立即执行(默认: false)
|
|
789
|
+
- `trailing?`: 最后一次调用后延迟执行(默认: true)
|
|
790
|
+
|
|
791
|
+
**返回:**
|
|
792
|
+
|
|
793
|
+
包含以下内容的对象:
|
|
794
|
+
|
|
795
|
+
- `run`: 使用参数执行防抖回调的函数
|
|
796
|
+
- `cancel`: 取消任何待处理防抖执行的函数
|
|
797
|
+
- `isPending`: 返回布尔值表示防抖执行当前是否待处理的函数
|
|
798
|
+
|
|
799
|
+
#### useDebouncedExecutePromise
|
|
800
|
+
|
|
801
|
+
```typescript
|
|
802
|
+
function useDebouncedExecutePromise<R = unknown, E = FetcherError>(
|
|
803
|
+
options: UseDebouncedExecutePromiseOptions<R, E>,
|
|
804
|
+
): UseDebouncedExecutePromiseReturn<R, E>;
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
将 Promise 执行与防抖功能相结合。
|
|
808
|
+
|
|
809
|
+
**类型参数:**
|
|
810
|
+
|
|
811
|
+
- `R`: Promise 结果的类型(默认为 unknown)
|
|
812
|
+
- `E`: 错误的类型(默认为 FetcherError)
|
|
813
|
+
|
|
814
|
+
**参数:**
|
|
815
|
+
|
|
816
|
+
- `options`: 包含 Promise 执行选项和防抖设置的配置对象
|
|
817
|
+
- `debounce`: 防抖配置(delay、leading、trailing)
|
|
818
|
+
- `UseExecutePromiseOptions` 的所有选项
|
|
819
|
+
|
|
820
|
+
**返回:**
|
|
821
|
+
|
|
822
|
+
包含以下内容的对象:
|
|
823
|
+
|
|
824
|
+
- `loading`: 布尔值,表示 Promise 当前是否正在执行
|
|
825
|
+
- `result`: Promise 的解析值
|
|
826
|
+
- `error`: 执行期间发生的任何错误
|
|
827
|
+
- `status`: 当前执行状态
|
|
828
|
+
- `run`: 使用提供的参数执行防抖 Promise 的函数
|
|
829
|
+
- `cancel`: 取消任何待处理防抖执行的函数
|
|
830
|
+
- `isPending`: 布尔值,表示防抖调用是否待处理
|
|
831
|
+
- `reset`: 将 hook 状态重置为初始值的函数
|
|
832
|
+
|
|
833
|
+
#### useDebouncedFetcher
|
|
834
|
+
|
|
835
|
+
```typescript
|
|
836
|
+
function useDebouncedFetcher<R, E = FetcherError>(
|
|
837
|
+
options: UseDebouncedFetcherOptions<R, E>,
|
|
838
|
+
): UseDebouncedFetcherReturn<R, E>;
|
|
839
|
+
```
|
|
840
|
+
|
|
841
|
+
专门的 hook,将 HTTP 获取与防抖相结合。
|
|
842
|
+
|
|
843
|
+
**类型参数:**
|
|
844
|
+
|
|
845
|
+
- `R`: 获取结果的类型
|
|
846
|
+
- `E`: 错误的类型(默认为 FetcherError)
|
|
847
|
+
|
|
848
|
+
**参数:**
|
|
849
|
+
|
|
850
|
+
- `options`: 扩展 `UseFetcherOptions` 和 `DebounceCapable` 的配置对象
|
|
851
|
+
- HTTP 请求选项(method、headers、timeout 等)
|
|
852
|
+
- `debounce`: 防抖配置(delay、leading、trailing)
|
|
853
|
+
|
|
854
|
+
**返回:**
|
|
855
|
+
|
|
856
|
+
包含以下内容的对象:
|
|
857
|
+
|
|
858
|
+
- `loading`: 布尔值,表示获取当前是否正在执行
|
|
859
|
+
- `result`: 获取的解析值
|
|
860
|
+
- `error`: 执行期间发生的任何错误
|
|
861
|
+
- `status`: 当前执行状态
|
|
862
|
+
- `exchange`: 表示正在进行的获取操作的 FetchExchange 对象
|
|
863
|
+
- `run`: 使用请求参数执行防抖获取的函数
|
|
864
|
+
- `cancel`: 取消任何待处理防抖执行的函数
|
|
865
|
+
- `isPending`: 布尔值,表示防抖调用是否待处理
|
|
866
|
+
|
|
635
867
|
### useFetcher
|
|
636
868
|
|
|
637
869
|
```typescript
|
package/dist/core/index.d.ts
CHANGED
package/dist/core/index.d.ts.map
CHANGED
|
@@ -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,93 @@
|
|
|
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/react';
|
|
67
|
+
*
|
|
68
|
+
* function SearchComponent() {
|
|
69
|
+
* const { loading, result, error, run } = useDebouncedExecutePromise({
|
|
70
|
+
* promise: async (query: string) => {
|
|
71
|
+
* const response = await fetch(`/api/search?q=${query}`);
|
|
72
|
+
* return response.json();
|
|
73
|
+
* },
|
|
74
|
+
* debounce: { delay: 300 },
|
|
75
|
+
* });
|
|
76
|
+
*
|
|
77
|
+
* const handleSearch = (query: string) => {
|
|
78
|
+
* run(query);
|
|
79
|
+
* };
|
|
80
|
+
*
|
|
81
|
+
* return (
|
|
82
|
+
* <div>
|
|
83
|
+
* <input onChange={(e) => handleSearch(e.target.value)} />
|
|
84
|
+
* {loading && <p>Searching...</p>}
|
|
85
|
+
* {result && <ul>{result.map(item => <li key={item.id}>{item.name}</li>)}</ul>}
|
|
86
|
+
* {error && <p>Error: {error.message}</p>}
|
|
87
|
+
* </div>
|
|
88
|
+
* );
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export declare function useDebouncedExecutePromise<R = unknown, E = FetcherError>(options: UseDebouncedExecutePromiseOptions<R, E>): UseDebouncedExecutePromiseReturn<R, E>;
|
|
93
|
+
//# 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;CAClB;AAED;;;;;;;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;CACvE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;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"}
|