Created
March 16, 2018 14:16
-
-
Save caub/bd6ba68193e306c8b98bc3d9f731cdcf 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
import React from 'react'; | |
/** | |
* Simple HOC, taking a fetcher function (returning a promise) then a Component | |
* @returns Component accepting a ({ data, error, loading }) => {..} function as children | |
*/ | |
export default fetcher => Component => | |
class extends React.PureComponent { | |
state = { loading: true, data: [], error: undefined }; | |
componentWillMount() { // todo refactor wrt https://github.com/reactjs/rfcs/blob/master/text/0006-static-lifecycle-methods.md | |
fetcher() | |
.then(data => { | |
this.setState({ data, loading: false }); | |
}) | |
.catch(error => { | |
this.setState({ error, loading: false }); | |
}); | |
} | |
render() { | |
const { children, ...props } = this.props; | |
return ( | |
<Component {...this.state} {...props}> | |
{typeof children === 'function' ? children(this.state) : children} | |
</Component> | |
); | |
} | |
}; | |
// maybe this hacky way would work too: | |
// export default fetcher => Component => { | |
// let data = [], loading = true, error; | |
// fetcher() | |
// .then(d => { | |
// data = d; | |
// loading = false; | |
// }) | |
// .catch(err => { | |
// error = err; | |
// loading = false; | |
// }); | |
// return ({ children, ...props }) => ( | |
// <Component data={data} loading={loading} error={error} {...props}> | |
// {typeof children === 'function' ? children({data, loading, state}) : children} | |
// </Component> | |
// ) | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment