useAsyncFunction
is a React hook that integrates an asynchronous function's
state with a React function component's state. This automates the process of
re-rendering the React function component as the asynchronous function's state
changes between pending, resolved, and rejected.
Install
npm i use-async-function
oryarn add use-async-function
Use
; const myAsyncFunction = async : Promise<void> await ; await ; return 'three';; { const dispatch = ; if !dispatchstate ; if dispatchstate === StateFulfilled return <div>The response was dispatchvalue</div>; if dispatchstate === StateRejected return <div>An error occurred: dispatcherror</div>; // Pending and uninitiated. return <Loading />;}
Parameters
useAsyncFunction(Function)
The first parameter of the useAsyncFunction
hook is the asynchronous function
itself.
useAsyncFunction(Function, Options)
If you are not using an identity reducer, the second
parameter of the useAsyncFunction
hook is the options object.
useAsyncFunction(Function, Reducer)
If you are using an identity reducer, the second parameter
of the useAsyncFunction
hook is the identity reducer.
useAsyncFunction(Function, Reducer, Options)
If you are using both an identity reducer and an
options object, the identity reducer is the second parameter of the
useAsyncFunction
hook, and the options object is the third parameter of the
useAsyncFunction
hook.
Identity Reducer
An identity reducer allows you to track multiple calls to the same asynchronous function. This is particularly useful when tracking API calls, where each call's fulfillment, pending, and rejection states are unique.
An identity reducer takes the call's arguments as its arguments and returns a string unique to that call.
// Asynchronously fetch a user's data by their username. { return ;} // Uniquely identify an asynchronous function call by the username. { return username;} { const dispatch = ; // We can determine if this call has been made by the presence of a property // with the call's ID. if !dispatchadmin ; return null; if !dispatchbob ; return null; // The state of the call is stored on the property with the call's ID. if dispatchadminstate === StateFulfilled return <div>Admin loaded with dispatchadminvalue</div>; }
Options
throwError
Default: false
Type: boolean
If true
, the asynchronous function will throw any encountered errors,
requiring a .catch
block.
If false
, the asynchronous function will swallow any errors. The component
will rerender, and the error
property of the async function will be set to the
caught error.
Sponsor 💗
If you are a fan of this project, you may become a sponsor via GitHub's Sponsors Program.