├── .gitignore
├── .prettierrc
├── .travis.yml
├── README.md
├── example
├── .npmignore
├── index.html
├── index.tsx
├── package.json
├── tsconfig.json
└── yarn.lock
├── package.json
├── src
└── index.ts
├── test
└── useAsync.test.ts
├── tsconfig.json
├── tsconfig.test.json
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | *.log
2 | .DS_Store
3 | node_modules
4 | .rts2_cache_cjs
5 | .rts2_cache_es
6 | .rts2_cache_esm
7 | .rts2_cache_umd
8 | dist
9 |
10 | example/.cache
11 |
12 | *.iml
13 | .idea
14 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "trailingComma": "all",
3 | "semi": true,
4 | "singleQuote": true,
5 | "tabWidth": 2,
6 | "useTabs": false,
7 | "bracketSpacing": true,
8 | "jsxBracketSameLine": false
9 | }
10 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - 8
4 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React-Async-Hook
2 |
3 | [](https://www.npmjs.com/package/react-async-hook)
4 | [](https://travis-ci.com/slorber/react-async-hook)
5 |
6 | This **tiny** library only **does one thing**, and **does it well**.
7 |
8 | ---
9 |
10 | # Sponsor
11 |
12 | **[ThisWeekInReact.com](https://thisweekinreact.com/react-async-hook)**: the best newsletter to stay up-to-date with the React ecosystem:
13 |
14 | [](https://thisweekinreact.com/react-async-hook)
15 |
16 | ---
17 |
18 | Don't expect it to grow in size, it is **feature complete**:
19 |
20 | - Handle fetches (`useAsync`)
21 | - Handle mutations (`useAsyncCallback`)
22 | - Handle cancellation (`useAsyncAbortable` + `AbortController`)
23 | - Handle [race conditions](https://sebastienlorber.com/handling-api-request-race-conditions-in-react)
24 | - Platform agnostic
25 | - Works with any async function, not just backend API calls, not just fetch/axios...
26 | - Very good, native, Typescript support
27 | - Small, no dependency
28 | - Rules of hooks: ESLint find missing dependencies
29 | - Refetch on params change
30 | - Can trigger manual refetch
31 | - Options to customize state updates
32 | - Can mutate state after fetch
33 | - Returned callbacks are stable
34 |
35 |
36 |
37 | ## Small size
38 |
39 | - Way smaller than popular alternatives
40 | - CommonJS + ESM bundles
41 | - Tree-shakable
42 |
43 | | Lib | min | min.gz |
44 | | -------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
45 | | **Suspend-React** | [](https://bundlephobia.com/package/suspend-react) | [](https://bundlephobia.com/package/suspend-react) |
46 | | **React-Async-Hook** | [](https://bundlephobia.com/package/react-async-hook) | [](https://bundlephobia.com/package/react-async-hook) |
47 | | **SWR** | [](https://bundlephobia.com/package/swr) | [](https://bundlephobia.com/package/swr) |
48 | | **React-Query** | [](https://bundlephobia.com/package/react-query) | [](https://bundlephobia.com/package/react-query) |
49 | | **React-Async** | [](https://bundlephobia.com/package/react-async) | [](https://bundlephobia.com/package/react-async) |
50 | | **Use-HTTP** | [](https://bundlephobia.com/package/use-http) | [](https://bundlephobia.com/package/use-http) |
51 | | **Rest-Hooks** | [](https://bundlephobia.com/package/rest-hooks) | [](https://bundlephobia.com/package/rest-hooks) |
52 |
53 | ---
54 |
55 | ## Things we don't support (by design):
56 |
57 | - stale-while-revalidate
58 | - refetch on focus / resume
59 | - caching
60 | - polling
61 | - request deduplication
62 | - platform-specific code
63 | - scroll position restoration
64 | - SSR
65 | - router integration for render-as-you-fetch pattern
66 |
67 | 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](https://github.com/vercel/swr) or [React-Query](https://github.com/tannerlinsley/react-query).
68 |
69 | ## Use-case: loading async data into a component
70 |
71 | The ability to inject remote/async data into a React component is a very common React need. Later we might support Suspense as well.
72 |
73 | ```tsx
74 | import { useAsync } from 'react-async-hook';
75 |
76 | const fetchStarwarsHero = async id =>
77 | (await fetch(`https://swapi.dev/api/people/${id}/`)).json();
78 |
79 | const StarwarsHero = ({ id }) => {
80 | const asyncHero = useAsync(fetchStarwarsHero, [id]);
81 | return (
82 |
83 | {asyncHero.loading &&
Loading
}
84 | {asyncHero.error &&
Error: {asyncHero.error.message}
}
85 | {asyncHero.result && (
86 |
87 |
Success!
88 |
Name: {asyncHero.result.name}
89 |
90 | )}
91 |
92 | );
93 | };
94 | ```
95 |
96 | ## Use-case: injecting async feedback into buttons
97 |
98 | 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.
99 |
100 | 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.
101 |
102 | ```tsx
103 | import { useAsyncCallback } from 'react-async-hook';
104 |
105 | const AppButton = ({ onClick, children }) => {
106 | const asyncOnClick = useAsyncCallback(onClick);
107 | return (
108 |
111 | );
112 | };
113 |
114 | const CreateTodoButton = () => (
115 | {
117 | await createTodoAPI('new todo text');
118 | }}
119 | >
120 | Create Todo
121 |
122 | );
123 | ```
124 |
125 | # Examples
126 |
127 | Examples are running on [this page](https://react-async-hook.netlify.com/) and [implemented here](https://github.com/slorber/react-async-hook/blob/master/example/index.tsx) (in Typescript)
128 |
129 | # Install
130 |
131 | `yarn add react-async-hook`
132 | or
133 |
134 | `npm install react-async-hook --save`
135 |
136 | ## ESLint
137 |
138 | If you use ESLint, use this [`react-hooks/exhaustive-deps`](https://github.com/facebook/react/blob/master/packages/eslint-plugin-react-hooks/README.md#advanced-configuration) setting:
139 |
140 | ```ts
141 | // .eslintrc.js
142 | module.exports = {
143 | // ...
144 | rules: {
145 | 'react-hooks/rules-of-hooks': 'error',
146 | 'react-hooks/exhaustive-deps': [
147 | 'error',
148 | {
149 | additionalHooks: '(useAsync|useAsyncCallback)',
150 | },
151 | ],
152 | },
153 | };
154 | ```
155 |
156 | # FAQ
157 |
158 | #### How can I debounce the request
159 |
160 | It is possible to debounce a promise.
161 |
162 | I recommend [awesome-debounce-promise](https://github.com/slorber/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)
163 |
164 | As debounced functions are stateful, we have to "store" the debounced function inside a component. We'll use for that [use-constant](https://github.com/Andarist/use-constant) (backed by `useRef`).
165 |
166 | ```tsx
167 | const StarwarsHero = ({ id }) => {
168 | // Create a constant debounced function (created only once per component instance)
169 | const debouncedFetchStarwarsHero = useConstant(() =>
170 | AwesomeDebouncePromise(fetchStarwarsHero, 1000)
171 | );
172 |
173 | // Simply use it with useAsync
174 | const asyncHero = useAsync(debouncedFetchStarwarsHero, [id]);
175 |
176 | return
...
;
177 | };
178 | ```
179 |
180 | #### How can I implement a debounced search input / autocomplete?
181 |
182 | 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.
183 | All this logic can easily be extracted into a single hook that you can reuse. Here is an example:
184 |
185 | ```tsx
186 | const searchStarwarsHero = async (
187 | text: string,
188 | abortSignal?: AbortSignal
189 | ): Promise => {
190 | const result = await fetch(
191 | `https://swapi.dev/api/people/?search=${encodeURIComponent(text)}`,
192 | {
193 | signal: abortSignal,
194 | }
195 | );
196 | if (result.status !== 200) {
197 | throw new Error('bad status = ' + result.status);
198 | }
199 | const json = await result.json();
200 | return json.results;
201 | };
202 |
203 | const useSearchStarwarsHero = () => {
204 | // Handle the input text state
205 | const [inputText, setInputText] = useState('');
206 |
207 | // Debounce the original search async function
208 | const debouncedSearchStarwarsHero = useConstant(() =>
209 | AwesomeDebouncePromise(searchStarwarsHero, 300)
210 | );
211 |
212 | const search = useAsyncAbortable(
213 | async (abortSignal, text) => {
214 | // If the input is empty, return nothing immediately (without the debouncing delay!)
215 | if (text.length === 0) {
216 | return [];
217 | }
218 | // Else we use the debounced api
219 | else {
220 | return debouncedSearchStarwarsHero(text, abortSignal);
221 | }
222 | },
223 | // Ensure a new request is made everytime the text changes (even if it's debounced)
224 | [inputText]
225 | );
226 |
227 | // Return everything needed for the hook consumer
228 | return {
229 | inputText,
230 | setInputText,
231 | search,
232 | };
233 | };
234 | ```
235 |
236 | And then you can use your hook easily:
237 |
238 | ```tsx
239 | const SearchStarwarsHeroExample = () => {
240 | const { inputText, setInputText, search } = useSearchStarwarsHero();
241 | return (
242 |
243 | setInputText(e.target.value)} />
244 |
245 | {search.loading &&
...
}
246 | {search.error &&
Error: {search.error.message}
}
247 | {search.result && (
248 |
249 |
Results: {search.result.length}
250 |
251 | {search.result.map(hero => (
252 |
{hero.name}
253 | ))}
254 |
255 |
256 | )}
257 |
258 |
259 | );
260 | };
261 | ```
262 |
263 | #### How to use request cancellation?
264 |
265 | You can use the `useAsyncAbortable` alternative. The async function provided will receive `(abortSignal, ...params)` .
266 |
267 | 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.
268 | It is your responsibility to wire the abort signal appropriately.
269 |
270 | ```tsx
271 | const StarwarsHero = ({ id }) => {
272 | const asyncHero = useAsyncAbortable(
273 | async (abortSignal, id) => {
274 | const result = await fetch(`https://swapi.dev/api/people/${id}/`, {
275 | signal: abortSignal,
276 | });
277 | if (result.status !== 200) {
278 | throw new Error('bad status = ' + result.status);
279 | }
280 | return result.json();
281 | },
282 | [id]
283 | );
284 |
285 | return
...
;
286 | };
287 | ```
288 |
289 | #### How can I keep previous results available while a new request is pending?
290 |
291 | It can be annoying to have the previous async call result be "erased" everytime a new call is triggered (default strategy).
292 | 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.
293 | It is possible to provide your own "merge" strategies.
294 | The following will ensure that on new calls, the previous result is kept until the new call result is received
295 |
296 | ```tsx
297 | const StarwarsHero = ({ id }) => {
298 | const asyncHero = useAsync(fetchStarwarsHero, [id], {
299 | setLoading: state => ({ ...state, loading: true }),
300 | });
301 | return
...
;
302 | };
303 | ```
304 |
305 | #### How to refresh / refetch the data?
306 |
307 | If your params are not changing, yet you need to refresh the data, you can call `execute()`
308 |
309 | ```tsx
310 | const StarwarsHero = ({ id }) => {
311 | const asyncHero = useAsync(fetchStarwarsHero, [id]);
312 |
313 | return
asyncHero.execute()}>...
;
314 | };
315 | ```
316 |
317 | #### How to handle conditional fetch?
318 |
319 | You can enable/disable the fetch logic directly inside the async callback. In some cases you know your API won't return anything useful.
320 |
321 | ```tsx
322 | const asyncSearchResults = useAsync(async () => {
323 | // It's useless to call a search API with an empty text
324 | if (text.length === 0) {
325 | return [];
326 | } else {
327 | return getSearchResultsAsync(text);
328 | }
329 | }, [text]);
330 | ```
331 |
332 | #### How to have better control when things get fetched/refetched?
333 |
334 | 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.
335 |
336 | In this case you'd better use a closure with no arg define in the dependency array which params should trigger a refetch:
337 |
338 | Here, both `state.a` and `state.b` will trigger a refetch, despite b is not passed to the async fetch function.
339 |
340 | ```tsx
341 | const asyncSomething = useAsync(() => fetchSomething(state.a), [
342 | state.a,
343 | state.b,
344 | ]);
345 | ```
346 |
347 | Here, only `state.a` will trigger a refetch, despite b being passed to the async fetch function.
348 |
349 | ```tsx
350 | const asyncSomething = useAsync(() => fetchSomething(state.a, state.b), [
351 | state.a,
352 | ]);
353 | ```
354 |
355 | 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:
356 |
357 | ```tsx
358 | const asyncSomething = useAsync(async () => {
359 | const payload = buildFetchPayload(state);
360 | const result = await fetchSomething(payload);
361 | return result;
362 | }), [state.a, state.b, state.whateverNeedToTriggerRefetch]);
363 | ```
364 |
365 | You can also use `useAsyncCallback` to decide yourself manually when a fetch should be done:
366 |
367 | ```tsx
368 | const asyncSomething = useAsyncCallback(async () => {
369 | const payload = buildFetchPayload(state);
370 | const result = await fetchSomething(payload);
371 | return result;
372 | }));
373 |
374 | // Call this manually whenever you need:
375 | asyncSomething.execute();
376 | ```
377 |
378 | #### How to support retry?
379 |
380 | Use a lib that adds retry feature to async/promises directly.
381 |
382 | # License
383 |
384 | MIT
385 |
386 | # Hire a freelance expert
387 |
388 | Looking for a React/ReactNative freelance expert with more than 5 years production experience?
389 | Contact me from my [website](https://sebastienlorber.com/) or with [Twitter](https://twitter.com/sebastienlorber).
390 |
--------------------------------------------------------------------------------
/example/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .cache
3 | dist
4 |
--------------------------------------------------------------------------------
/example/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Playground
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/example/index.tsx:
--------------------------------------------------------------------------------
1 | import 'react-app-polyfill/ie11';
2 | import * as React from 'react';
3 | import * as ReactDOM from 'react-dom';
4 | import '@babel/polyfill';
5 |
6 | import {
7 | useAsync,
8 | useAsyncAbortable,
9 | useAsyncCallback,
10 | UseAsyncReturn,
11 | } from 'react-async-hook';
12 |
13 | import { ReactNode, useState } from 'react';
14 | import useConstant from 'use-constant';
15 | import AwesomeDebouncePromise from 'awesome-debounce-promise';
16 |
17 | const AppButton = ({ onClick, children }) => {
18 | const asyncOnClick = useAsyncCallback(onClick);
19 | return (
20 |
27 | );
28 | };
29 |
30 | type ExampleType = 'basic' | 'abortable' | 'debounced' | 'merge';
31 |
32 | type StarwarsHero = {
33 | id: string;
34 | name: string;
35 | };
36 |
37 | const fetchStarwarsHero = async (
38 | id: string,
39 | abortSignal?: AbortSignal
40 | ): Promise => {
41 | const result = await fetch(`https://swapi.dev/api/people/${id}/`, {
42 | signal: abortSignal,
43 | });
44 | if (result.status !== 200) {
45 | throw new Error('bad status = ' + result.status);
46 | }
47 | return result.json();
48 | };
49 |
50 | const searchStarwarsHero = async (
51 | text: string,
52 | abortSignal?: AbortSignal
53 | ): Promise => {
54 | const result = await fetch(
55 | `https://swapi.dev/api/people/?search=${encodeURIComponent(text)}`,
56 | {
57 | signal: abortSignal,
58 | }
59 | );
60 | if (result.status !== 200) {
61 | throw new Error('bad status = ' + result.status);
62 | }
63 | const json = await result.json();
64 | return json.results;
65 | };
66 |
67 | const HeroContainer = ({ children }) => (
68 |