-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeout.js
More file actions
87 lines (72 loc) · 1.65 KB
/
timeout.js
File metadata and controls
87 lines (72 loc) · 1.65 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import { Component } from 'react'
import PropTypes from 'prop-types'
export default class Timeout extends Component {
static propTypes = {
ms: PropTypes.number,
suspense: PropTypes.node,
children: PropTypes.func.isRequired
}
static defaultProps = {
ms: 0,
suspense: null
}
state = {
inSuspense: false,
didExpire: false
}
_expireTimeout = null
_suspender = null
componentDidCatch(err, info) {
if (typeof err.then === 'function') {
const suspender = err
this._suspender = suspender
this._initTimeout()
this.setState({ inSuspense: true })
const update = () => {
if (this._suspender !== suspender) return
this.setState({ inSuspense: false })
this._clearTimeout()
if (this.state.didExpire) {
this.setState({ didExpire: false })
} else {
this.forceUpdate()
}
}
suspender.then(update, update)
} else {
// rethrow non-promise errors
throw err
}
}
render() {
const {
children,
suspense
} = this.props
const {
inSuspense,
didExpire
} = this.state
if (inSuspense && !didExpire) {
// optional: strictly for the purpose of demoing how suspense works
return suspense
} else {
return children(didExpire)
}
}
_initTimeout() {
const {
ms
} = this.props
this._clearTimeout()
this._expireTimeout = setTimeout(() => {
this.setState({ didExpire: true })
}, ms)
}
_clearTimeout() {
if (this._expireTimeout) {
clearTimeout(this._expireTimeout)
this._expireTimeout = null
}
}
}