-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathusePromise.js
More file actions
36 lines (31 loc) · 756 Bytes
/
usePromise.js
File metadata and controls
36 lines (31 loc) · 756 Bytes
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
var React = require('react')
var flattenInput = require('./utils/flattenInput')
function usePromise (
callFunction
) {
var inputs = Array.prototype.slice.call(arguments, [1])
var state = React.useState({
isLoading: !!callFunction
})
React.useEffect(function () {
if (!callFunction) {
return
}
!state[0].isLoading && state[1]({ data: state[0].data, isLoading: true })
callFunction.apply(null, inputs)
.then(function (data) {
state[1]({
data: data,
isLoading: false
})
})
.catch(function (error) {
state[1]({
error: error,
isLoading: false
})
})
}, flattenInput(inputs))
return state[0]
}
module.exports = usePromise