Skip to content

Instantly share code, notes, and snippets.

@gigobyte
Last active May 15, 2017 18:48
Show Gist options
  • Save gigobyte/dd26629e25047adba6407a154186412b to your computer and use it in GitHub Desktop.
Save gigobyte/dd26629e25047adba6407a154186412b to your computer and use it in GitHub Desktop.
const fetchResources = (mapResourcesToProps) => (ComposedComponent) => {
return class extends React.Component {
static displayName = `Fetch(${ComposedComponent.displayName || ComposedComponent.name})`
state = {}
componentDidMount() {
const mapResult = mapResourcesToProps(this.props)
const resourceProps = Object.keys(mapResult)
const resourcePromises = Object.values(mapResult)
Promise.all(resourcePromises).then(resources => {
this.setState(resources.reduce((newState, resource, i) => {
newState[resourceProps[i]] = resource;
return newState
}, {}))
})
}
render() {
if (Object.keys(this.state).length === 0) {
return null;
}
return <ComposedComponent {...this.props} {...this.state} />
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment