useAsync()
The
useAsync() hook simplifies asynchronous logic management (like API calls) by providing reactive states for pending, success, and error outcomes.Import
typescript
Usage
Status:idle
Component.tsx
API
Arguments
asyncFunction– (...args: any[]) => Promise<T> The function to be executed. Must return a Promise.immediate– boolean (Optional) If true, the function will be executed immediately on mount. Defaults to false.
Returns
Returns an object with the following properties:
execute– (...args) => Promise Function to manually trigger the async operation.status– 'idle' | 'pending' | 'success' | 'error' Current state of the operation.value– T | null The resolved data from the promise (if successful).error– E | null The error object (if rejected).isPending– boolean Helper boolean, true if status is 'pending'.