Created
August 18, 2017 17:17
-
-
Save fdaciuk/36ed9336782503fe32cea9cb1a059c89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
import React, { PureComponent } from 'react' | |
import t from 'prop-types' | |
const loadAsync = (promise) => { | |
class Async extends PureComponent { | |
constructor () { | |
super() | |
this.state = { | |
loaded: false, | |
Component: null | |
} | |
this.mounted = true | |
this.getDisplayName = (Comp) => ( | |
Comp.displayName || Comp.name || 'UnknownComponent' | |
) | |
} | |
async componentDidMount () { | |
try { | |
const Comp = await promise | |
const LoadedComp = Comp.default | |
if (this.mounted) { | |
this.setState({ loaded: true, Component: LoadedComp }) | |
Async.displayName = `Async(${this.getDisplayName(LoadedComp)})` | |
} | |
} catch (e) { | |
console.error(e.stack) | |
} | |
} | |
componentWillUnmount () { | |
this.mounted = false | |
} | |
render () { | |
return this.state.loaded | |
? <this.state.Component {...this.props} /> | |
: <div children={this.props.children} /> | |
} | |
} | |
Async.propTypes = { | |
children: t.node | |
} | |
return Async | |
} | |
export default loadAsync |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import loadAsync from './load-async' | |
const ContentAsync = loadAsync(import('./content')) | |
const App = () => ( | |
<ContentAsync /> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment