useAsync
SourceHook to deal with triggering async function calls and handling result / errors and loading states.
This can be used in two distinct modes:
- manual (
useAsync.MANUAL
) - the function is only triggered explicitly - automatic (
useAsync.DEEP
oruseAsync.SHALLOW
) - the function is triggered initially and then automatically when argument values change (using a shallow or deep comparison).
For mutations you usually want manual as it is triggered in response to some user action like pressing a button.
For data fetching you usually want automatic mode as you retrieve some data initially and then refetch it when some arguments change (eg. the id for a single record or the filters for a list).
Examples
Fetch and render a specified github profile
Parameter | Type | Description | |
---|---|---|---|
* | fn | Function | A function that returns a promise. When |
options.args | Array | Arguments to be passed to asyncFn when it is called. Can be empty. If you are using | |
options.onError | Function | Called when action errors. Passed the error returned from async action. See note above on | |
options.onSuccess | Function | Called when action resolves successfully. Is passed a single parameter which is the result from the async action. NOTE: If your component unmounts before the promise resolves this function
will NOT be called. This is to avoid the general case of calling React
state transition functions on an unmounted component. If you want the
method to be called regardless then attach your own callbacks to the
promise when you call | |
options.trigger | "MANUAL"|"SHALLOW"|"DEEP" | Determines when the function is called. Defaults to NOTE: If changing from MANUAL then the function will be called immediately regardless useAsync.MANUAL (default) - only called when you explicitly call useAsync.SHALLOW - called whenever a shallow equality check fails. Compares previous async function,
and useAsync.DEEP - called whenever a deep equality check fails. Compares previous async function and
|
Key | Type | Description |
---|---|---|
error | ErrorT|null | Set to the rejected value of the promise. Only one of |
isLoading | boolean | True when action is in progress. |
reset | Function | When called will set both result or error to null. Will not immediately trigger
a call to the action but subsequent changes to |
response | ResultT|null | Deprecated: Use `result` instead |
result | ResultT|null | Set to the resolved value of promise. Only one of |
run | Function | A function to manually trigger the action. If This function will return a promise that resolves/rejects to same value resolved/rejected from the async action. |