Skip to main content

useLoading()

Helps track loading state of imperative async functions.

tip

useSuspense() or useDLE() are better for GET/read endpoints.

Usage

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

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];

Examples

Github pagination

More Demos

Github comment form submission

More Demos