-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathasyncComponent.js
More file actions
247 lines (216 loc) · 6.69 KB
/
asyncComponent.js
File metadata and controls
247 lines (216 loc) · 6.69 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import React from 'react'
import PropTypes from 'prop-types'
const validSSRModes = ['resolve', 'defer', 'boundary']
function asyncComponent(config) {
const {
name,
resolve,
autoResolveES2015Default = true,
serverMode = 'resolve',
LoadingComponent,
ErrorComponent,
} = config
if (validSSRModes.indexOf(serverMode) === -1) {
throw new Error('Invalid serverMode provided to asyncComponent')
}
const env =
['node', 'browser'].indexOf(config.env) > -1
? config.env
: typeof window === 'undefined' ? 'node' : 'browser'
const sharedState = {
// A unique id we will assign to our async component which is especially
// useful when rehydrating server side rendered async components.
id: null,
// This will be use to hold the resolved module allowing sharing across
// instances.
// NOTE: When using React Hot Loader this reference will become null.
module: null,
// If an error occurred during a resolution it will be stored here.
error: null,
// Allows us to share the resolver promise across instances.
resolver: null,
}
// Takes the given module and if it has a ".default" the ".default" will
// be returned. i.e. handy when you could be dealing with es6 imports.
const es6Resolve = x =>
autoResolveES2015Default &&
x != null &&
(typeof x === 'function' || typeof x === 'object') &&
x.default
? x.default
: x
const getResolver = () => {
if (sharedState.resolver == null) {
try {
// Wrap whatever the user returns in Promise.resolve to ensure a Promise
// is always returned.
const resolver = resolve()
sharedState.resolver = Promise.resolve(resolver)
} catch (err) {
sharedState.resolver = Promise.reject(err)
}
}
return sharedState.resolver
}
class AsyncComponent extends React.Component {
constructor(props, context) {
super(props, context)
// We have to set the id in the constructor because a RHL seems
// to recycle the module and therefore the id closure will be null.
// We can't put it in componentWillMount as RHL hot swaps the new code
// so the mount call will not happen (but the ctor does).
if (this.context.asyncComponents != null && !sharedState.id) {
sharedState.id = this.context.asyncComponents.getNextId()
}
}
// @see react-async-bootstrapper
asyncBootstrap() {
const { asyncComponents, asyncComponentsAncestor } = this.context
const { shouldRehydrate } = asyncComponents
const doResolve = () =>
this.resolveModule().then(module => module !== undefined)
if (env === 'browser') {
return shouldRehydrate(sharedState.id) ? doResolve() : false
}
// node
const isChildOfBoundary =
asyncComponentsAncestor != null && asyncComponentsAncestor.isBoundary
return serverMode === 'defer' || isChildOfBoundary ? false : doResolve()
}
getChildContext() {
if (this.context.asyncComponents == null) {
return {
asyncComponentsAncestor: null,
}
}
return {
asyncComponentsAncestor: {
isBoundary: serverMode === 'boundary',
},
}
}
componentWillMount() {
this.setState({
module: sharedState.module,
})
if (sharedState.error) {
this.registerErrorState(sharedState.error)
}
}
componentDidMount() {
if (this.shouldResolve()) {
this.resolveModule()
}
}
shouldResolve() {
return (
sharedState.module == null &&
sharedState.error == null &&
!this.resolving &&
typeof window !== 'undefined'
)
}
resolveModule() {
this.resolving = true
return getResolver()
.then(module => {
if (this.unmounted) {
return undefined
}
if (this.context.asyncComponents != null) {
this.context.asyncComponents.resolved(sharedState.id)
}
sharedState.module = module
if (env === 'browser') {
this.setState({
module,
})
}
this.resolving = false
return module
})
.catch(error => {
if (this.unmounted) {
return undefined
}
if (env === 'node' || (env === 'browser' && !ErrorComponent)) {
// We will at least log the error so that user isn't completely
// unaware of an error occurring.
// eslint-disable-next-line no-console
console.warn('Failed to resolve asyncComponent')
// eslint-disable-next-line no-console
console.warn(error)
}
sharedState.error = error
this.registerErrorState(error)
this.resolving = false
return undefined
})
}
retryResolvingModule() {
// clear existing errors
this.registerErrorState(null)
sharedState.error = null
// clear resolver so it'll be retried
sharedState.resolver = null
this.resolveModule()
}
componentWillUnmount() {
this.unmounted = true
}
registerErrorState(error) {
if (env === 'browser') {
setTimeout(() => {
if (!this.unmounted) {
this.setState({
error,
})
}
}, 16)
}
}
render() {
const { module, error } = this.state
if (error) {
return ErrorComponent ? (
<ErrorComponent
{...this.props}
retry={() => this.retryResolvingModule()}
error={error}
/>
) : null
}
// This is as workaround for React Hot Loader support. When using
// RHL the local component reference will be killed by any change
// to the component, this will be our signal to know that we need to
// re-resolve it.
if (this.shouldResolve()) {
this.resolveModule()
}
const Component = es6Resolve(module)
return Component ? (
<Component {...this.props} />
) : LoadingComponent ? (
<LoadingComponent {...this.props} />
) : null
}
}
AsyncComponent.displayName = name || 'AsyncComponent'
AsyncComponent.contextTypes = {
asyncComponentsAncestor: PropTypes.shape({
isBoundary: PropTypes.bool,
}),
asyncComponents: PropTypes.shape({
getNextId: PropTypes.func.isRequired,
resolved: PropTypes.func.isRequired,
shouldRehydrate: PropTypes.func.isRequired,
}),
}
AsyncComponent.childContextTypes = {
asyncComponentsAncestor: PropTypes.shape({
isBoundary: PropTypes.bool,
}),
}
return AsyncComponent
}
export default asyncComponent