|
31 | 31 | </a>
|
32 | 32 | </p>
|
33 | 33 |
|
34 |
| -React component for declarative promise resolution and data fetching. Leverages the Render Props pattern for ultimate |
35 |
| -flexibility as well as the new Context API for ease of use. Makes it easy to handle loading and error states, without |
36 |
| -assumptions about the shape of your data or the type of request. |
| 34 | +React component for declarative promise resolution and data fetching. Leverages the Render Props pattern and Hooks for |
| 35 | +ultimate flexibility as well as the new Context API for ease of use. Makes it easy to handle loading and error states, |
| 36 | +without assumptions about the shape of your data or the type of request. |
37 | 37 |
|
38 | 38 | - Zero dependencies
|
39 | 39 | - Works with any (native) promise
|
40 |
| -- Choose between Render Props and Context-based helper components |
| 40 | +- Choose between Render Props, Context-based helper components or the `useAsync` hook |
41 | 41 | - Provides convenient `isLoading`, `startedAt` and `finishedAt` metadata
|
42 | 42 | - Provides `cancel` and `reload` actions
|
43 | 43 | - Automatic re-run using `watch` prop
|
@@ -71,6 +71,28 @@ npm install --save react-async
|
71 | 71 |
|
72 | 72 | ## Usage
|
73 | 73 |
|
| 74 | +As a hook with `useAsync`: |
| 75 | + |
| 76 | +```js |
| 77 | +import { useAsync } from "react-async" |
| 78 | + |
| 79 | +const loadJson = () => fetch("/some/url").then(res => res.json()) |
| 80 | + |
| 81 | +const MyComponent = () => { |
| 82 | + const { data, error, isLoading } = useAsync({ promiseFn: loadJson }) |
| 83 | + if (isLoading) return "Loading..." |
| 84 | + if (error) return `Something went wrong: ${error.message}` |
| 85 | + if (data) |
| 86 | + return ( |
| 87 | + <div> |
| 88 | + <strong>Loaded some data:</strong> |
| 89 | + <pre>{JSON.stringify(data, null, 2)}</pre> |
| 90 | + </div> |
| 91 | + ) |
| 92 | + return null |
| 93 | +} |
| 94 | +``` |
| 95 | + |
74 | 96 | Using render props for ultimate flexibility:
|
75 | 97 |
|
76 | 98 | ```js
|
|
0 commit comments