useAsync
This hook simplifies the execution of an async
function by returning its states and results.
Parameters
- an async function (a function that returns a promise).
Return Values
Name | Type | Description |
---|---|---|
data | callback return type | resolved data from the function. |
isPending | Boolean | the loading state. |
callback | Fnuction | the async callback function. |
error | Unknown | cached error if it exists. |
Example Usage
tsx
import { useAsync } from 'react-pre-hooks';
const getData = (ms: number) => {
return new Promise<string>(res => setTimeout(() => res('Resolved!'), ms));
};
export default function Example() {
const { data, isPending, callback } = useAsync(async () => {
return await getData(2200);
});
return (
<main>
<div>{isPending ? 'Loading...' : data ?? 'No data.'}</div>
<button onClick={callback}>Start</button>
</main>
);
}
import { useAsync } from 'react-pre-hooks';
const getData = (ms: number) => {
return new Promise<string>(res => setTimeout(() => res('Resolved!'), ms));
};
export default function Example() {
const { data, isPending, callback } = useAsync(async () => {
return await getData(2200);
});
return (
<main>
<div>{isPending ? 'Loading...' : data ?? 'No data.'}</div>
<button onClick={callback}>Start</button>
</main>
);
}