wait-hooks
v1.1.0
Published
tiny async hooks for react
Maintainers
Readme
This package exposes two basic hooks: useWait and useDeferWait.
useWait
is a simple hook that waits for a promise to resolve:
import { useWait } from 'wait-hooks'; // 341 B
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { message: 'Hello World' };
}
function Component() {
const { status, data, isLoading, error } = useWait(getData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
Message: {data.message}
</div>
);
}useDeferWait
allows to defer the execution of an async function:
import { useDeferWait } from 'wait-hooks'; // 429 B
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { message: 'Hello World' };
}
function Component() {
const { status, data, isLoading, error, run } = useDeferWait(getData);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<button onClick={() => run()}>Run</button>
{data && <div>Message: {data.message}</div>}
</div>
);
}