项目作者: we-code-now

项目描述 :
Playing with async task in React
高级语言: JavaScript
项目地址: git://github.com/we-code-now/react-hook-use-async.git
创建时间: 2019-08-20T08:56:58Z
项目社区:https://github.com/we-code-now/react-hook-use-async

开源协议:MIT License

下载


react-hook-use-async

npm Build Status Codacy Badge Codacy Badge npm bundle size GitHub

Give me an async task, I’ll give you its insights!

Table of Contents

Features

  • Simple and flexible!
  • Render async task’s result without headache.
  • Get notified when the async task is complete via onSuccess(), onError(), onCancel() callbacks.
  • Support automatically and on-demand re-execute via execute().
  • Support automatically and on-demand cancellation via cancel().

Installation

  1. $ npm install --save react-hook-use-async

Problem

Async task is a very common stuff in application. For example, fetch todo list, follow a person, upload images… and we need a convenient way to execute an async task and render its result when the task is complete. This package provides a convenient hook to deal with them. Let’s see examples and FAQ below.

Examples

Fetching user

  1. import useAsync from 'react-hook-use-async';
  2. function fetchUserById([id]) {
  3. const url = `http://example.com/fetch-user?id=${id}`;
  4. return fetch(url).then(response => response.json());
  5. }
  6. function User({ id }) {
  7. const task = useAsync(fetchUserById, [id]);
  8. return (
  9. <div>
  10. {task.isPending && (
  11. <div>
  12. <div>Fetching...</div>
  13. <button type="button" onClick={task.cancel}>
  14. Cancel
  15. </button>
  16. </div>
  17. )}
  18. {task.error && <div>Error: {task.error.message}</div>}
  19. {task.result && (
  20. <div>
  21. <div>User: {task.result.name}</div>
  22. <button
  23. type="button"
  24. onClick={task.execute}
  25. disabled={task.isPending}
  26. >
  27. Refetch
  28. </button>
  29. </div>
  30. )}
  31. </div>
  32. );
  33. }

Following user

  1. import useAsync from 'react-hook-use-async';
  2. function followUserById([id]) {
  3. const url = 'http://example.com/follow-user';
  4. const config = {
  5. method: 'POST',
  6. body: JSON.stringify({ id }),
  7. };
  8. return fetch(url, config);
  9. }
  10. function FollowUserBtn({ id }) {
  11. const task = useAsync(followUserById, [id], { isOnDemand: true });
  12. return (
  13. <button type="button" onClick={task.execute} disabled={task.isPending}>
  14. Follow
  15. </button>
  16. );
  17. }

Get notified when task is complete

  1. import useAsync from 'react-hook-use-async';
  2. function FollowUserBtn({ id }) {
  3. const task = useAsync(followUserById, [id], {
  4. isOnDemand: true,
  5. onSuccess: (result, [id]) => {
  6. const message = `Followed user ${id}, you are number ${result.rank} in fan-ranking`;
  7. console.log(message);
  8. },
  9. onError: (error, [id]) => {
  10. const message = `Got error while trying to follow user ${id}: ${error.message}`;
  11. console.log(message);
  12. },
  13. onCancel: ([id]) => {
  14. const message = `Canceled following user ${id}`;
  15. console.log(message);
  16. },
  17. });
  18. return (
  19. <button type="button" onClick={task.execute} disabled={task.isPending}>
  20. Follow
  21. </button>
  22. );
  23. }

Providing custom cancellation

  1. import useAsync, { Task } from 'react-hook-use-async';
  2. function fetchUserById([id]) {
  3. const url = `http://example.com/fetch-user?id=${id}`;
  4. const controller = (typeof AbortController !== 'undefined' ? new AbortController() : null);
  5. const config = { signal: controller && controller.signal };
  6. const promise = fetch(url, config).then(response => response.json());
  7. const cancel = () => controller && controller.abort();
  8. return new Task(promise, cancel);
  9. }
  10. function User({ id }) {
  11. const task = useAsync(fetchUserById, [id]);
  12. ...
  13. }
  1. import useAsync, { Task } from 'react-hook-use-async';
  2. function fetchArticles([query]) {
  3. const url = `http://example.com/fetch-articles?query=${query}`;
  4. const controller = (typeof AbortController !== 'undefined' ? new AbortController() : null);
  5. const config = { signal: controller && controller.signal };
  6. let timeoutId = null;
  7. const promise = new Promise((resolve, reject) => {
  8. timeoutId = setTimeout(() => {
  9. fetch(url, config).then(response => response.json()).then(resolve).catch(reject);
  10. }, 300);
  11. });
  12. const cancel = () => {
  13. timeoutId && clearTimeout(timeoutId);
  14. controller && controller.abort();
  15. };
  16. return new Task(promise, cancel);
  17. }
  18. function Articles({ query }) {
  19. const task = useAsync(fetchArticles, [query]);
  20. ...
  21. }

API

useAsync

  1. const {
  2. // async task error, default: undefined
  3. error,
  4. // async task result, default: undefined
  5. result,
  6. // promise of current async task, default: undefined
  7. promise,
  8. // async task is pending or not, default: false
  9. isPending,
  10. // cancel current async task on-demand
  11. cancel,
  12. // execute current async task on-demand
  13. execute,
  14. } = useAsync(
  15. // (inputs) => Promise
  16. //
  17. // A function which get called to create async task, using `inputs`.
  18. //
  19. // It should return a promise, but actually it can return any value.
  20. createTask,
  21. // any[], default: []
  22. //
  23. // This array is used to create task. If it changes, the old task will
  24. // be canceled and a new task will be created. If your inputs shape
  25. // seems unchange but a new task still be created infinitely, the reason
  26. // is because React uses `Object.is()` comparison algorithm, shallow
  27. // comparison. In short, inputs must be an array of primitives, else
  28. // you should memoize non-primitive values for yourself.
  29. //
  30. // Other note: size MUST BE consistent between renders!
  31. inputs,
  32. // optional config
  33. config: {
  34. // boolean, default: false
  35. //
  36. // This flag provides two modes.
  37. // In proactive mode (false), an async task will be executed automatically when `inputs` changes.
  38. // In on-demand mode (true), an async task will be executed only when `execute()` get called.
  39. //
  40. // Note: only its value in the first render will be used. This means mode can't be changed.
  41. isOnDemand,
  42. // (error, inputs) => void
  43. //
  44. // Error callback will get called when async task get any errors.
  45. onError,
  46. // (inputs) => void
  47. //
  48. // Cancel callback will get called when async task is canceled.
  49. onCancel,
  50. // (result, inputs) => void
  51. //
  52. // Success callback will get called when async task is success.
  53. onSuccess,
  54. },
  55. );

Feature Comparison

Feature useAsync() useAsync() (isOnDemand = true)
Execute on mount
Re-execute on inputs changes
Re-execute on-demand
Cancel on unmount
Cancel on re-execute
Cancel on-demand
Get notified when task is complete

Migrating from v1 to v2

  • Missing useAsyncOnDemand() hook. Use useAsync() with isOnDemand = true.
  • Missing injection as second argument of createTask(). See Providing custom cancellation if you want to cancel request using fetch() API. I drop this because of two reason. First, an async task can be anything, not only about data fetching. Provide injection for every calls can be annoying. Last, in v1, I supported fetch() API only, but in fact, any libraries can be used, such as axios, request… So it’s not great. Instead, in v2, I provide you a convenient way to put any cancellation method to maximize usability.

FAQ

When the async task will be executed?

Let me show you two common use cases:

  • Data fetching - Data should be fetched on the component gets mounted and inputs changes, such as apply filters using form. You also want to put a Fetch button to let you fetch data on-demand whenever you want. In this case, you must use useAsync() hook with proactive mode.
  • Click-to-action-button - You don’t want any automatic mechanism. You want to click a button to do something, such as follow a person or you want to refetch data after you delete a data item. In this case, you must use useAsync() hook with on-demand mode.

Why I got infinite re-fetch loop when using useAsync() hook?

Be sure inputs doesn’t change in every render. Understanding by examples:

  1. function Example({ id }) {
  2. // your `inputs`: [ { id } ]
  3. // BUT `{ id }` is always new in every render!
  4. const task = useAsync(([{ id }]) => fetchSomethingById(id), [{ id }]);
  5. }

Why is there no new async task execution when inputs changes?

If you use useAsync() hook in proactive mode, be sure inputs changes and size of inputs must be the same between renders.

  1. function Example({ ids }) {
  2. // first render: ids = [1, 2, 3], inputs = [1, 2, 3]
  3. // second render: ids = [1, 2], inputs = [1, 2]
  4. // size changes => don't execute new async task!
  5. const task = useAsync(ids => doSomething(ids), ids);
  6. }

If you use useAsync() hook in on-demand mode, you must execute on-demand. See below for details.

Why is there no new async task execution when createTask() changes every render?

Because of convenient. Sometimes you might want to write code like this and you don’t expect re-execution happens:

  1. function Example({ id }) {
  2. // createTask() changes every render!
  3. const task = useAsync(([id]) => doSomething(id), [id]);
  4. // DO NOT use write this code!
  5. // const task = useAsync(() => doSomething(id), []);
  6. }

Make createTask() depends on inputs as param, move it out of React component if possible for clarification.

What happens when inputs changes when using useAsync() hook in on-demand mode?

No execution at all. When you execute on-demand, the latest inputs will be used to create a new async task.

Can I manually execute an async task at any time?

Yes. Via execute() function in useAsync() result.

  1. function Example() {
  2. const { execute } = useAsync(...);
  3. }

Is cancellation is supported?

Yes. An async task will be canceled before a new async task to be executed or when the component gets unmounted.

Can I manually cancel the async task at any time?

Yes. Via cancel() function in useAsync() result.

  1. function Example({ id }) {
  2. const { cancel } = useAsync(...);
  3. }

What happens when isOnDemand changes?

Nothing happens.

When we get notified about completed task via onSuccess(), onError() or onCancel(), which version of callback is used?

No matter how often callback changes, its version in the same execution render will be used.

Demo

License

MIT