Skip to content

Instantly share code, notes, and snippets.

@iinsta
Last active October 23, 2017 16:36
Show Gist options
  • Save iinsta/aa444537ebc6921713db70f3435b602f to your computer and use it in GitHub Desktop.
Save iinsta/aa444537ebc6921713db70f3435b602f to your computer and use it in GitHub Desktop.
react async load componet demo
/*
* opts = {
* load: () => import('./DemoComponent'), error: function(props) { return <div onClick={props.reload}>Load error</div>}
* }
*
*/
import React, {BasicComponent} from 'ReactBasicComponent'
function asyncLoad(opts) {
const {load, error as ErrorComponent, Loading} = opts;
return class AsyncLoad extends BasicComponent {
state = {
component: null,
status: 'loading',
}
didMount() {
this.load()
}
load => {
this.state.status === 'error' && this.updateState({
status: 'loading',
})
load().then(res => {
this.updateState({
status: 'ok',
component: res
})
}).catch(e => {
this.updateState({
status: 'e'
})
})
}
render() {
const {component, status} = this.state
let TmpComponent = null
switch(status) {
case null:
break
case 'loading':
TmpComponent = <Loading />
break
case 'error':
TmpComponent = <ErrorComponent reload={this.load}/>
break
default:
TmpComponent = <component />
}
return TmpComponent
}
}
}
import React from 'react'
export default React
export class BasicComponent extends React.Component {
componentWillUnmount() {
this.willUnmount && this.willUnmount()
this.__unmount = true
}
componentDidMount() {
this.didMount && this.didMount()
}
updateState(){
this.__unmount && this.setState(...arguments)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment