useAsync Hook
A React hook for executing asynchronous functions with loading, error, and result states.
Installation
Usage
Options
The useAsync
hook accepts the following options:
onError
: A callback to execute when an error occurs.
onSuccess
: A callback to execute when the promise resolves successfully.
Pass the options as the second argument:
Dependencies
You can provide dependencies to the useCallback
hook by passing them as the third argument:
API
useAsync
Forcing return type
If you want to force the return type of the asynchronous function, you can do so by providing a generic type argument:
This will enforce that the return type of the asynchronous function is string
.
It will not validate the return type of the asynchronous function at runtime. It is only a compile-time check.
Parameters
fn
: The asynchronous function to execute.
options
: Options to customize the behavior of the hook.
dependencies
: Dependencies to pass to the useCallback
hook.
Return Value
An object with the following properties:
execute
: A function to trigger the execution of the asynchronous function.
loading
: A boolean indicating whether the function is currently executing.
error
: An error object if an error occurred during execution, otherwise null
.
result
: The result of the asynchronous function if it executed successfully, otherwise null
.
Example
Links
use-async.ts