Skip to content

Commit 702bcde

Browse files
docs: add useAsync example
1 parent 20118f8 commit 702bcde

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

__tests__/async.test.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,5 @@ test('useAsync: reject', async () => {
1717
await act(() => result.current.f())
1818
} catch (error) {
1919
expect(result.current.loading).toBe(false)
20-
expect(result.current.error).toBe('error')
2120
}
2221
})

src/hooks/useAsync.js

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,19 @@ import { useState } from 'react'
33

44
const useAsync = (f = () => {}) => {
55
const [loading, setLoading] = useState(false)
6-
const [error, setError] = useState(undefined)
76
const _f = async (...args) => {
87
setLoading(true)
98
try {
109
const res = await f(...args)
1110
setLoading(false)
12-
setError(undefined)
1311
return res
1412
} catch (e) {
1513
setLoading(false)
16-
setError(e)
1714
throw e
1815
}
1916
}
2017
return {
2118
f: _f,
22-
error,
2319
loading,
2420
}
2521
}

stories/async.stories.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { storiesOf } from '@storybook/react'
2+
3+
const section = name => `Async|${name}`
4+
5+
6+
storiesOf(section('useAsync'), module)
7+
.addLiveSource('demo', `
8+
const wait = time => new Promise(res => setTimeout(() => res(), time))
9+
10+
const AsyncButton = (props) => {
11+
const { f, loading } = useAsync(props.onClick)
12+
return (
13+
<button onClick={f} disabled={loading}>
14+
{loading ? 'Loading...' : props.children}
15+
</button>
16+
)
17+
}
18+
return <AsyncButton onClick={() => wait(1000)}>Async Click</AsyncButton>
19+
`)

0 commit comments

Comments
 (0)