Skip to content

Commit 4228229

Browse files
committed
add getAbortController apis
1 parent d802c73 commit 4228229

35 files changed

+2409
-167
lines changed

docs/config.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@
8989
{
9090
"label": "Async Batching Guide",
9191
"to": "guides/async-batching"
92+
},
93+
{
94+
"label": "Async Retrying Guide",
95+
"to": "guides/async-retrying"
9296
}
9397
]
9498
},

docs/framework/react/reference/functions/useasyncretryer.md

Lines changed: 50 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,43 @@ function useAsyncRetryer<TFn, TSelected>(
1414
selector): ReactAsyncRetryer<TFn, TSelected>
1515
```
1616

17-
Defined in: [react-pacer/src/async-retryer/useAsyncRetryer.ts:152](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-retryer/useAsyncRetryer.ts#L152)
17+
Defined in: [react-pacer/src/async-retryer/useAsyncRetryer.ts:194](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-retryer/useAsyncRetryer.ts#L194)
1818

1919
A low-level React hook that creates an `AsyncRetryer` instance to retry execution of an async function.
2020

2121
This hook is designed to be flexible and state-management agnostic - it simply returns a retryer instance that
2222
you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
2323

24+
## Retrying Concepts
25+
2426
Async retrying automatically re-executes a failed async function up to a specified number of attempts with
2527
configurable backoff strategies. This is useful for handling transient errors like network failures, temporary
2628
server issues, or rate limiting where you want to automatically retry the operation.
2729

28-
Error Handling:
29-
- If an `onError` handler is provided, it will be called for every error during execution
30-
- If an `onLastError` handler is provided, it will be called only for the final error after all retries fail
31-
- If `throwOnError` is 'last' (default), only the final error after all retries will be thrown
32-
- If `throwOnError` is true, every error will be thrown immediately (disables retrying)
33-
- If `throwOnError` is false, errors are never thrown and undefined is returned instead
30+
- **Backoff Strategies**: Controls the delay between retry attempts (default: `'exponential'`):
31+
- `'exponential'`: Wait time doubles with each attempt (1s, 2s, 4s, ...) - **DEFAULT**
32+
- `'linear'`: Wait time increases linearly (1s, 2s, 3s, ...)
33+
- `'fixed'`: Waits a constant amount of time (`baseWait`) between each attempt
34+
- **Jitter**: Adds randomness to retry delays to prevent thundering herd problems (default: `0`).
35+
Set to a value between 0-1 to apply that percentage of random variation to each delay.
36+
- **Timeout Controls**: Set limits on execution time to prevent hanging operations:
37+
- `maxExecutionTime`: Maximum time for a single function call (default: `Infinity`)
38+
- `maxTotalExecutionTime`: Maximum time for the entire retry operation (default: `Infinity`)
39+
- **Abort & Cancellation**: Call `abort()` on the retryer to cancel ongoing execution and pending retries.
40+
41+
## Error Handling
42+
43+
The `throwOnError` option controls when errors are thrown (default: `'last'`):
44+
- `'last'`: Only throws the final error after all retries are exhausted - **DEFAULT**
45+
- `true`: Throws every error immediately (disables retrying)
46+
- `false`: Never throws errors, returns `undefined` instead
47+
48+
Callbacks for error handling:
49+
- `onError`: Called for every error (including during retries)
50+
- `onLastError`: Called only for the final error after all retries fail
51+
- `onRetry`: Called before each retry attempt
52+
- `onSuccess`: Called when execution succeeds
53+
- `onSettled`: Called after execution completes (success or failure)
3454

3555
## State Management and Selector
3656

@@ -53,6 +73,10 @@ Available state properties:
5373
- `status`: Current execution status ('disabled' | 'idle' | 'executing' | 'retrying')
5474
- `totalExecutionTime`: Total time spent executing (including retries) in milliseconds
5575

76+
## Cleanup
77+
78+
The hook automatically calls `abort()` on unmount to cancel any ongoing execution.
79+
5680
## Type Parameters
5781

5882
**TFn** *extends* `AnyAsyncFunction`
@@ -90,6 +114,23 @@ const apiRetryer = useAsyncRetryer(
90114
{ maxAttempts: 3, backoff: 'exponential' }
91115
);
92116
117+
// With advanced retry configuration
118+
const apiRetryer = useAsyncRetryer(
119+
async (userId: string) => {
120+
const response = await fetch(`/api/users/${userId}`);
121+
if (!response.ok) throw new Error('Failed to fetch user');
122+
return response.json();
123+
},
124+
{
125+
maxAttempts: 5,
126+
backoff: 'exponential',
127+
baseWait: 1000,
128+
jitter: 0.1, // Add 10% random variation to prevent thundering herd
129+
maxExecutionTime: 5000, // Abort individual calls after 5 seconds
130+
maxTotalExecutionTime: 30000, // Abort entire operation after 30 seconds
131+
}
132+
);
133+
93134
// Opt-in to re-render when execution state changes (optimized for loading indicators)
94135
const apiRetryer = useAsyncRetryer(
95136
async (userId: string) => {
@@ -129,7 +170,8 @@ const apiRetryer = useAsyncRetryer(
129170
maxAttempts: 3,
130171
backoff: 'exponential',
131172
onError: (error) => console.error('API call failed:', error),
132-
onLastError: (error) => console.error('All retries failed:', error)
173+
onLastError: (error) => console.error('All retries failed:', error),
174+
onRetry: (attempt, error) => console.log(`Retry attempt ${attempt} after error:`, error),
133175
},
134176
(state) => ({
135177
lastError: state.lastError,

0 commit comments

Comments
 (0)