Skip to content

Commit 24355b3

Browse files
committed
Update readme
1 parent eaff4ab commit 24355b3

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,52 @@ const { result, pending, error, refresh } = useAsync(() => {
1111
```
1212

1313
The `useAsync` hook allows you to call asynchronous closures and retrieve the output in a painless way, and at the same time reduce the number of unnecessary rerenderings. It follows the convention of the standard react hooks in terms of the second dependency array.
14+
15+
Whenever the dependency array is changed, the async operation will be reapplied. However, when an operation is ongoing any subsequent updates will be skipped. The last update that was skipped will be executed once the first operation is completed. Which means that the result should always be eventually consistent with the triggering state. This behavior is most likely what you want when async operation is fetching some data or the like. If you are updating data as a side effect, it would be better to use `useAsyncCallback` instead, since that unsures that all operations will be executed.
16+
17+
## useAsyncCallback
18+
19+
```tsx
20+
function PostEditView({ postId }) {
21+
const [title, setTitle] = useState();
22+
const [body, setBody] = useState();
23+
const { result, pending, error, execute } = useAsyncCallback(() => {
24+
return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
25+
method: 'PATCH',
26+
body: JSON.stringify({
27+
title,
28+
body,
29+
}),
30+
headers: {
31+
'Content-type': 'application/json; charset=UTF-8',
32+
},
33+
});
34+
}, []);
35+
return <button onClick={execute}>Submit</button>;
36+
}
37+
```
38+
39+
```tsx
40+
function PostEditView({ postId }) {
41+
const [title, setTitle] = useState();
42+
const [body, setBody] = useState();
43+
const { result, pending, error, execute } = useAsyncCallback(
44+
(title, body) => {
45+
return fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`, {
46+
method: 'PATCH',
47+
body: JSON.stringify({
48+
title,
49+
body,
50+
}),
51+
headers: {
52+
'Content-type': 'application/json; charset=UTF-8',
53+
},
54+
});
55+
},
56+
[]
57+
);
58+
return <button onClick={() => execute(title, body)}>Submit</button>;
59+
}
60+
```
61+
62+
Both examples above leads to the same outcome. Use whichever way fits your situation best, either passing data as arguments to `execute` or using the closure to pass the data. `execute` will always use the latest closure even though it is referentially stable.

0 commit comments

Comments
 (0)