Skip to content

Instantly share code, notes, and snippets.

@fdaciuk
Created August 18, 2017 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fdaciuk/36ed9336782503fe32cea9cb1a059c89 to your computer and use it in GitHub Desktop.
Save fdaciuk/36ed9336782503fe32cea9cb1a059c89 to your computer and use it in GitHub Desktop.
'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
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