Last active
August 13, 2016 13:48
-
-
Save tanapoln/f3439b13dada865e3944e81b56af5fc5 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
import React from 'react' | |
import { RouterContext } from 'react-router' | |
import _ from 'lodash' | |
export default class AsyncComp extends React.Component { | |
constructor(props, context) { | |
super(props, context) | |
this.state = { | |
loading : false, | |
currentProp: props, | |
data : props.data | |
} | |
this.loadData = this.loadData.bind(this) | |
} | |
static propTypes = { | |
components: React.PropTypes.array.isRequired, | |
data : React.PropTypes.any | |
} | |
static fetchData(props) { | |
const arr = [] | |
props.components.forEach((comp, idx) => { | |
if (!comp) return; | |
if (!comp.fetchData) return; | |
arr.push(comp.fetchData(props.params)) | |
}) | |
return Promise.all(arr) | |
.then((dataArr) => _.merge.apply(_, dataArr)) | |
} | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.location === this.props.location) | |
return | |
this.loadData(nextProps) | |
} | |
componentWillMount() { | |
if (!this.state.data) { | |
this.loadData(this.props) | |
} | |
} | |
loadData(props) { | |
this.setState({ | |
loading: true | |
}) | |
AsyncComp.fetchData(props) | |
.then((data) => { | |
this.setState({ | |
loading : false, | |
currentProp: props, | |
data : data | |
}) | |
}) | |
} | |
render() { | |
const {loading, currentProp, data} = this.state; | |
return <RouterContext {...currentProp} createElement={(Component, props) => { | |
return <Component {...props} data={data}/> | |
}}/> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment