-
Notifications
You must be signed in to change notification settings - Fork 925
Expand file tree
/
Copy pathwithLoadjs.jsx
More file actions
99 lines (83 loc) · 2.49 KB
/
Copy pathwithLoadjs.jsx
File metadata and controls
99 lines (83 loc) · 2.49 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
88
89
90
91
92
93
94
95
96
97
98
99
import _ from "lodash"
import invariant from "invariant"
import canUseDOM from "can-use-dom"
import { getDisplayName } from "recompose"
import PropTypes from "prop-types"
import React from "react"
const LOADING_STATE_NONE = `NONE`
const LOADING_STATE_BEGIN = `BEGIN`
const LOADING_STATE_LOADED = `LOADED`
const LOADING_STATE_FAILED = `FAILED`
export function withLoadjs(BaseComponent) {
const factory = React.createFactory(BaseComponent)
class Container extends React.PureComponent {
static displayName = `withLoadjs(${getDisplayName(BaseComponent)})`
static propTypes = {
loadingElement: PropTypes.node.isRequired,
failedElement: PropTypes.node.isRequired,
googleMapURL: PropTypes.string.isRequired,
}
state = {
loadingState: LOADING_STATE_NONE,
}
isUnmounted = false
handleLoaded = _.bind(this.handleLoaded, this)
handleLoaded(error) {
if (this.isUnmounted) {
return
}
this.setState({
loadingState: error ? LOADING_STATE_FAILED : LOADING_STATE_LOADED,
})
}
componentWillMount() {
const { loadingElement, googleMapURL } = this.props
invariant(
!!loadingElement && !!googleMapURL,
`Required props loadingElement or googleMapURL is missing. You need to provide both of them.`
)
}
componentDidMount() {
const { loadingState } = this.state
if (loadingState !== LOADING_STATE_NONE || !canUseDOM) {
return
}
this.setState({
loadingState: LOADING_STATE_BEGIN,
})
// Don't load scriptjs as a dependency since we do not want this module be used on server side.
// eslint-disable-next-line global-require
const loadjs = require(`load-js`)
const { googleMapURL } = this.props
loadjs([
{
url: googleMapURL,
async: true,
},
])
.then(() => this.handleLoaded())
.catch(this.handleLoaded)
}
componentWillUnmount() {
this.isUnmounted = true
}
render() {
const {
loadingElement,
failedElement,
googleMapURL, // eslint-disable-line no-unused-vars
...restProps
} = this.props
const { loadingState } = this.state
if (loadingState === LOADING_STATE_LOADED) {
return factory(restProps)
} else if (loadingState === LOADING_STATE_FAILED) {
return failedElement
} else {
return loadingElement
}
}
}
return Container
}
export default withLoadjs