Skip to content

Instantly share code, notes, and snippets.

@vojtatranta
Created February 22, 2017 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vojtatranta/47ce5b1a04c81fe5e45b0190a89bfc28 to your computer and use it in GitHub Desktop.
Save vojtatranta/47ce5b1a04c81fe5e45b0190a89bfc28 to your computer and use it in GitHub Desktop.
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