useLoading
useLoading
is a React hook that simplifies managing the loading state of a Promise
. It provides a state to track whether an asynchronous operation is in progress and a function to handle the loading state automatically.
Interface
ts
function useLoading(): [
loading: boolean,
startLoading: <T>(promise: Promise<T>) => Promise<T>,
];
Parameters
Return Value
- [loading: boolean, startLoading: <T>(promise: Promise<T>) => Promise<T>]
tuple containing:
- loadingboolean
Represents the current loading state.
: The initial value isfalse
.
: It is set totrue
when an asynchronous task is in progress. - startLoading<T>(promise: Promise<T>) => Promise<T>
A function that executes asynchronous tasks while managing the loading state.
: This function takes aPromise
as an argument and automatically resets theisLoading
state tofalse
when thePromise
completes.
- loadingboolean
Example
tsx
function ConfirmButton() {
const [loading, startLoading] = useLoading();
const handleSubmit = useCallback(async () => {
try {
const result = await startLoading(postConfirmation());
router.push(`/success?id=${result.id}`);
} catch (error) {
console.error('Error:', error);
}
}, [startLoading]);
return (
<button disabled={loading} onClick={handleSubmit}>
{loading ? 'Loading...' : 'Confirm'}
</button>
);
}