useLoading()
Helps track loading and error state of imperative async functions.
tip
useSuspense() or useDLE() are better for GET/read endpoints.
Usage
PostResource
PostDetail
PostForm
PostCreate
import { useLoading, useController } from '@data-client/react'; import { PostResource } from './PostResource'; import PostForm from './PostForm'; export default function PostCreate() { const ctrl = useController(); const navigate = useNavigate(); const [handleSubmit, loading, error] = useLoading( async data => { const post = await ctrl.fetch(PostResource.getList.push, data); navigate(`/posts/${post.id}`); }, [ctrl, navigate], ); return ( <PostForm onSubmit={handleSubmit} loading={loading} error={error} /> ); }
Like useCallback, takes a dependency list to ensure referential consistency of the function.
Eslint
Eslint configuration
Since we use the deps list, be sure to add useLoading to the 'additionalHooks' configuration of react-hooks/exhaustive-deps rule if you use it.
{
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "(useLoading)"
}]
}
}
Types
export default function useLoading<
F extends (...args: any) => Promise<any>,
>(func: F, deps: readonly any[] = []): [F, boolean, Error | undefined];
loading is true while the returned promise is pending. If func rejects, the rejection is
caught and stored in error; it is cleared again on the next call. When calls overlap, loading and
error follow the latest call, so an earlier call that settles later doesn't change them.
Examples
Github pagination
Explore the github-app example
Github comment form submission
Explore the github-app example