WarningRetries will not be triggered if a request is manually aborted or if the component unmounts during the process.
ImportantWhen implementing optimistic updates via mutate, you must manually handle the state reversal inside a try/catch block within the execute call.
TipUse the params configuration to automatically serialize objects into URL query strings, avoiding manual string concatenation.
The useAsyncState hook provides a full-featured lifecycle management system for asynchronous requests. It eliminates the boilerplate of manually handling loading, error, and data states, while offering advanced features like automatic retries, request timeouts, URL parameter serialization, optimistic updates via mutate, and request cancellation via AbortController.
| Name | Type | Description |
|---|---|---|
| options.initialData | T | null | The initial value for the data state. Default is null. |
| options.onSuccess | (data: T) => void | Global callback triggered when any request initialed by this hook succeeds. |
| options.onError | (error: Error) => void | Global callback triggered when a request fails after all retries are exhausted. |
| Name | Type | Description |
|---|---|---|
| data | T | null | The current data returned by the last successful asynchronous operation. |
| error | Error | null | The error object if the last operation failed. |
| isLoading | boolean | true if a request is currently in progress. |
| isError | boolean | true if the last operation resulted in an error. |
| isSuccess | boolean | true if the last operation completed successfully. |
| isIdle | boolean | true if no request has been initiated yet. |
| execute | (url: string, config?: FetchConfig) => Promise<T | null> | Function to trigger a new request with custom headers, params, and retry settings. |
| mutate | (data: T) => void | Directly updates the local data state (useful for optimist UI updates). |
| reset | () => void | Cancels pending requests and restores the state to its initial values. |
| retry | () => Promise<T | null> | Re-executes the last request using the exact same configuration and URL. |