-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseAsync.js
More file actions
42 lines (35 loc) · 1 KB
/
useAsync.js
File metadata and controls
42 lines (35 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import React from 'react'
function asyncReducer(state, action) {
switch (action.type) {
case 'pending': {
return {status: 'pending', data: null, error: null}
}
case 'resolved': {
return {status: 'resolved', data: action.data, error: null}
}
case 'rejected': {
return {status: 'rejected', data: null, error: action.error}
}
default: {
throw new Error(`Unhandled action type: ${action.type}`)
}
}
}
const useAsync = (initialState) => {
const [state, dispatch] = React.useReducer(asyncReducer, {
status: 'idle',
data: null,
error: null,
...initialState
})
const run = React.useCallback(promise => {
dispatch({type: 'pending'})
promise.then(data => {
dispatch({type: 'resolved', data})
}, error => {
dispatch({type: 'rejected', error})
})
}, [])
return {...state, run}
}
export default useAsync