Skip to content

Instantly share code, notes, and snippets.

@caub
Created March 16, 2018 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caub/bd6ba68193e306c8b98bc3d9f731cdcf to your computer and use it in GitHub Desktop.
Save caub/bd6ba68193e306c8b98bc3d9f731cdcf to your computer and use it in GitHub Desktop.
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