-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathasync.js
55 lines (52 loc) · 1.17 KB
/
async.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
import React, {PropTypes} from 'react'
class Async extends React.Component {
constructor (props) {
super(props)
this.state = {}
}
componentWillReceiveProps (nP) {
if (nP.promise !== this.props.promise) {
this.state = {}
this.forceUpdate()
this.handlePromise(nP.promise)
}
}
handlePromise (prom) {
prom.then((res) => {
this.setState({
resolved: res,
finished: true
})
}, (err) => {
this.setState({
rejected: err,
finished: true
})
})
}
componentWillMount () {
this.handlePromise(this.props.promise)
}
render () {
const {props, state} = this
if (!state.finished) {
if (props.pendingRender) {
return props.pendingRender // custom component to indicate load in progress
}
return <div></div>
}
if (props.then && state.resolved) {
return props.then(state.resolved)
}
if (props.catch && state.rejected) {
return props.catch(state.rejected)
}
}
}
Async.propTypes = {
then: PropTypes.func,
catch: PropTypes.func,
pendingRender: PropTypes.node,
promise: PropTypes.object.isRequired
}
export default Async