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
Navigation
import { useLoading, useController } from '@data-client/react'; import { PostResource } from './PostResource'; import PostForm from './PostForm'; export default function PostCreate({ navigateToPost }) { const ctrl = useController(); const [handleSubmit, loading, error] = useLoading( async data => { const post = await ctrl.fetch(PostResource.getList.push, data); navigateToPost(post.id); }, [ctrl], ); return ( <PostForm onSubmit={handleSubmit} loading={loading} error={error} /> ); }
🔴 Live Preview
Store▶
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];