Created
February 22, 2017 07:58
-
-
Save vojtatranta/47ce5b1a04c81fe5e45b0190a89bfc28 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
const createApiComponent = (requestFn, initialState = {}) => (component) => { | |
return class extends React.Component { | |
state = { loading: false, ...initialState } | |
componentDidMount() { | |
this.setState({ loading: true }) | |
requestFn() | |
.then(apiResult => { this.setState({ apiResult, loading: false }) }) | |
.catch(apiError => { this.setState({ apiError, loading: false }) }) | |
} | |
render() { | |
return component({ ...this.props, ...this.state }) | |
} | |
} | |
} | |
// usage | |
class Page extends React.Component { | |
render() { | |
if (this.props.loading) { return <div>Loading...</div> } | |
return <div>result is: {this.props.apiResult.body}</div> | |
} | |
} | |
const apiPage = createApiComponent(() => fetch('/my/url'))(Page) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment