• Stars
    star
    1,140
  • Rank 40,879 (Top 0.9 %)
  • Language
    TypeScript
  • Created about 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

React hook to handle any async operation in React components, and prevent race conditions

React-Async-Hook

NPM Build Status

This tiny library only does one thing, and does it well.


Sponsor

ThisWeekInReact.com: the best newsletter to stay up-to-date with the React ecosystem:

ThisWeekInReact.com banner


Don't expect it to grow in size, it is feature complete:

  • Handle fetches (useAsync)
  • Handle mutations (useAsyncCallback)
  • Handle cancellation (useAsyncAbortable + AbortController)
  • Handle race conditions
  • Platform agnostic
  • Works with any async function, not just backend API calls, not just fetch/axios...
  • Very good, native, Typescript support
  • Small, no dependency
  • Rules of hooks: ESLint find missing dependencies
  • Refetch on params change
  • Can trigger manual refetch
  • Options to customize state updates
  • Can mutate state after fetch
  • Returned callbacks are stable

Small size

  • Way smaller than popular alternatives
  • CommonJS + ESM bundles
  • Tree-shakable
Lib min min.gz
Suspend-React
React-Async-Hook
SWR
React-Query
React-Async
Use-HTTP
Rest-Hooks

Things we don't support (by design):

  • stale-while-revalidate
  • refetch on focus / resume
  • caching
  • polling
  • request deduplication
  • platform-specific code
  • scroll position restoration
  • SSR
  • router integration for render-as-you-fetch pattern

You can build on top of this little lib to provide more advanced features (using composition), or move to popular full-featured libraries like SWR or React-Query.

Use-case: loading async data into a component

The ability to inject remote/async data into a React component is a very common React need. Later we might support Suspense as well.

import { useAsync } from 'react-async-hook';

const fetchStarwarsHero = async id =>
  (await fetch(`https://swapi.dev/api/people/${id}/`)).json();

const StarwarsHero = ({ id }) => {
  const asyncHero = useAsync(fetchStarwarsHero, [id]);
  return (
    <div>
      {asyncHero.loading && <div>Loading</div>}
      {asyncHero.error && <div>Error: {asyncHero.error.message}</div>}
      {asyncHero.result && (
        <div>
          <div>Success!</div>
          <div>Name: {asyncHero.result.name}</div>
        </div>
      )}
    </div>
  );
};

Use-case: injecting async feedback into buttons

If you have a Todo app, you might want to show some feedback into the "create todo" button while the creation is pending, and prevent duplicate todo creations by disabling the button.

Just wire useAsyncCallback to your onClick prop in your primitive AppButton component. The library will show a feedback only if the button onClick callback is async, otherwise it won't do anything.

import { useAsyncCallback } from 'react-async-hook';

const AppButton = ({ onClick, children }) => {
  const asyncOnClick = useAsyncCallback(onClick);
  return (
    <button onClick={asyncOnClick.execute} disabled={asyncOnClick.loading}>
      {asyncOnClick.loading ? '...' : children}
    </button>
  );
};

const CreateTodoButton = () => (
  <AppButton
    onClick={async () => {
      await createTodoAPI('new todo text');
    }}
  >
    Create Todo
  </AppButton>
);

Examples

Examples are running on this page and implemented here (in Typescript)

Install

yarn add react-async-hook or

npm install react-async-hook --save

ESLint

If you use ESLint, use this react-hooks/exhaustive-deps setting:

// .eslintrc.js
module.exports = {
  // ...
  rules: {
    'react-hooks/rules-of-hooks': 'error',
    'react-hooks/exhaustive-deps': [
      'error',
      {
        additionalHooks: '(useAsync|useAsyncCallback)',
      },
    ],
  },
};

FAQ

How can I debounce the request

It is possible to debounce a promise.

I recommend awesome-debounce-promise, as it handles nicely potential concurrency issues and have React in mind (particularly the common use-case of a debounced search input/autocomplete)

As debounced functions are stateful, we have to "store" the debounced function inside a component. We'll use for that use-constant (backed by useRef).

const StarwarsHero = ({ id }) => {
  // Create a constant debounced function (created only once per component instance)
  const debouncedFetchStarwarsHero = useConstant(() =>
    AwesomeDebouncePromise(fetchStarwarsHero, 1000)
  );

  // Simply use it with useAsync
  const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]);

  return <div>...</div>;
};

How can I implement a debounced search input / autocomplete?

This is one of the most common use-case for fetching data + debouncing in a component, and can be implemented easily by composing different libraries. All this logic can easily be extracted into a single hook that you can reuse. Here is an example:

const searchStarwarsHero = async (
  text: string,
  abortSignal?: AbortSignal
): Promise<StarwarsHero[]> => {
  const result = await fetch(
    `https://swapi.dev/api/people/?search=${encodeURIComponent(text)}`,
    {
      signal: abortSignal,
    }
  );
  if (result.status !== 200) {
    throw new Error('bad status = ' + result.status);
  }
  const json = await result.json();
  return json.results;
};

const useSearchStarwarsHero = () => {
  // Handle the input text state
  const [inputText, setInputText] = useState('');

  // Debounce the original search async function
  const debouncedSearchStarwarsHero = useConstant(() =>
    AwesomeDebouncePromise(searchStarwarsHero, 300)
  );

  const search = useAsyncAbortable(
    async (abortSignal, text) => {
      // If the input is empty, return nothing immediately (without the debouncing delay!)
      if (text.length === 0) {
        return [];
      }
      // Else we use the debounced api
      else {
        return debouncedSearchStarwarsHero(text, abortSignal);
      }
    },
    // Ensure a new request is made everytime the text changes (even if it's debounced)
    [inputText]
  );

  // Return everything needed for the hook consumer
  return {
    inputText,
    setInputText,
    search,
  };
};

And then you can use your hook easily:

const SearchStarwarsHeroExample = () => {
  const { inputText, setInputText, search } = useSearchStarwarsHero();
  return (
    <div>
      <input value={inputText} onChange={e => setInputText(e.target.value)} />
      <div>
        {search.loading && <div>...</div>}
        {search.error && <div>Error: {search.error.message}</div>}
        {search.result && (
          <div>
            <div>Results: {search.result.length}</div>
            <ul>
              {search.result.map(hero => (
                <li key={hero.name}>{hero.name}</li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
};

How to use request cancellation?

You can use the useAsyncAbortable alternative. The async function provided will receive (abortSignal, ...params) .

The library will take care of triggering the abort signal whenever a new async call is made so that only the last request is not cancelled. It is your responsibility to wire the abort signal appropriately.

const StarwarsHero = ({ id }) => {
  const asyncHero = useAsyncAbortable(
    async (abortSignal, id) => {
      const result = await fetch(`https://swapi.dev/api/people/${id}/`, {
        signal: abortSignal,
      });
      if (result.status !== 200) {
        throw new Error('bad status = ' + result.status);
      }
      return result.json();
    },
    [id]
  );

  return <div>...</div>;
};

How can I keep previous results available while a new request is pending?

It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy). If you are implementing some kind of search/autocomplete dropdown, it means a spinner will appear everytime the user types a new char, giving a bad UX effect. It is possible to provide your own "merge" strategies. The following will ensure that on new calls, the previous result is kept until the new call result is received

const StarwarsHero = ({ id }) => {
  const asyncHero = useAsync(fetchStarwarsHero, [id], {
    setLoading: state => ({ ...state, loading: true }),
  });
  return <div>...</div>;
};

How to refresh / refetch the data?

If your params are not changing, yet you need to refresh the data, you can call execute()

const StarwarsHero = ({ id }) => {
  const asyncHero = useAsync(fetchStarwarsHero, [id]);

  return <div onClick={() => asyncHero.execute()}>...</div>;
};

How to handle conditional fetch?

You can enable/disable the fetch logic directly inside the async callback. In some cases you know your API won't return anything useful.

const asyncSearchResults = useAsync(async () => {
  // It's useless to call a search API with an empty text
  if (text.length === 0) {
    return [];
  } else {
    return getSearchResultsAsync(text);
  }
}, [text]);

How to have better control when things get fetched/refetched?

Sometimes you end up in situations where the function tries to fetch too often, or not often, because your dependency array changes and you don't know how to handle this.

In this case you'd better use a closure with no arg define in the dependency array which params should trigger a refetch:

Here, both state.a and state.b will trigger a refetch, despite b is not passed to the async fetch function.

const asyncSomething = useAsync(() => fetchSomething(state.a), [
  state.a,
  state.b,
]);

Here, only state.a will trigger a refetch, despite b being passed to the async fetch function.

const asyncSomething = useAsync(() => fetchSomething(state.a, state.b), [
  state.a,
]);

Note you can also use this to "build" a more complex payload. Using useMemo does not guarantee the memoized value will not be cleared, so it's better to do:

const asyncSomething = useAsync(async () => {
  const payload = buildFetchPayload(state);
  const result = await fetchSomething(payload);
  return result;
}), [state.a, state.b, state.whateverNeedToTriggerRefetch]);

You can also use useAsyncCallback to decide yourself manually when a fetch should be done:

const asyncSomething = useAsyncCallback(async () => {
  const payload = buildFetchPayload(state);
  const result = await fetchSomething(payload);
  return result;
}));

// Call this manually whenever you need:
asyncSomething.execute();

How to support retry?

Use a lib that adds retry feature to async/promises directly.

License

MIT

Hire a freelance expert

Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.

More Repositories

1

react-native-scroll-into-view

Scroll a ReactNative View into the visible screen. Similar to DOMElement.scrollIntoView() browser function.
TypeScript
409
star
2

awesome-debounce-promise

Debounce your API calls easily and stay in promised land.
TypeScript
376
star
3

scalable-frontend-with-elm-or-redux

An attempt to make Redux and Elm applications scale
JavaScript
363
star
4

trailing-slash-guide

Understand and fix your static website trailing slash issues!
HTML
307
star
5

gatsby-plugin-react-native-web

react-native-web plugin for Gatsby
JavaScript
277
star
6

react-native-animation-hooks

A simple declarative API for React-Native animations, using hooks
TypeScript
243
star
7

combine-promises

Like Promise.all(array) but with an object instead of an array.
TypeScript
202
star
8

rereduce

Reducer library for Redux
JavaScript
166
star
9

ajax-interceptor

This permits to wire interceptors on XHR requests and responses
JavaScript
122
star
10

react-reboot

The easiest way to refresh your React components with up-to-date syntax.
JavaScript
62
star
11

react-nested-loader

The easiest way to manage loaders/errors inside a button. NOT an UI lib.
JavaScript
62
star
12

sebastienlorber.com

My personal website
JavaScript
58
star
13

gcm-server-repository

maven repository for gcm-server for Android push notifications
Shell
46
star
14

react-native-alert-async

An Alert.alert that you can await
JavaScript
45
star
15

awesome-imperative-promise

Offer an imperative API on top of promise, with cancellation support
TypeScript
41
star
16

micro-typed-events

The smallest, most convenient typesafe TS event emitter you'll ever need
TypeScript
40
star
17

todomvc-onboarding

Showcase different ways to add a complex onboarding to a TodoMVC app
36
star
18

use-async-setState

Permits to await setState()
TypeScript
35
star
19

expo-typescript

TypeScript
33
star
20

redux-dispatch-subscribe

store enhancer for redux which allows to listen for dispatched actions
JavaScript
29
star
21

react-three-fiber-journey

Three.js Journey implemented with React-Three-Fiber
TypeScript
27
star
22

awesome-only-resolves-last-promise

Wraps an async function, and ensures that only last call will ever resolve/reject
TypeScript
26
star
23

docusaurus-crowdin-example

JavaScript
11
star
24

backspace-disabler

Disable the annoying browser backward navigation when the user press the backspace key
JavaScript
11
star
25

react-native-storage-slot

A simple typed wrapper around AsyncStorage
TypeScript
10
star
26

slorber

8
star
27

awesome-icu

Reference everything you find interesting about ICU translations
7
star
28

this-week-in-react

ThisWeekInReact.com
MDX
6
star
29

slo.im

slo.im shortcuts
4
star
30

react-updatable-context

React context which inject a value setter/updater in the Consumer
JavaScript
3
star
31

slorber-website

My website
JavaScript
2
star
32

test-docu

JavaScript
2
star
33

expo-ci

JavaScript
2
star
34

traced-svg-parameter-chooser

JavaScript
2
star
35

docusaurus-visual-tests

TypeScript
2
star
36

docusaurus-starter

JavaScript
1
star
37

bug-expokit-crashlytics

bug-expokit-crashlytics
JavaScript
1
star
38

slorber-api-screenshot

JavaScript
1
star
39

docusaurus-dsfr

TypeScript
1
star