Last active
May 15, 2017 18:48
-
-
Save gigobyte/dd26629e25047adba6407a154186412b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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