Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created March 4, 2018 21:18
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 sobstel/c0624c21d5fdf3172e00b5f77b929622 to your computer and use it in GitHub Desktop.
Save sobstel/c0624c21d5fdf3172e00b5f77b929622 to your computer and use it in GitHub Desktop.
Loader/loading Higher-Order Component
// Sample usage: (taken from https://github.com/sobstel/golazon)
//
// class Competition extends Component {
// (...)
// }
//
// const fetchData = ({ id }) => {
// return competitionService.competition(id).then(competition => ({ competition }));
// };
//
// export default loadable(fetchData)(Competition);
//
export default (fetchData) => {
return (WrappedComponent) => {
return class extends Component {
state = {
data: false,
loader: false,
error: false
}
componentDidMount () {
this.setState({ loader: true });
fetchData(this.props).then((data) => {
this.setState({ data, loader: false });
}).catch((err) => {
this.setState({ error: err.message, loader: false });
});
}
render () {
return (
<div>
{this.state.loader &&
<div class="block wrapped">
<p class="loader">
loading
</p>
</div>
}
{this.state.error &&
<div class="block wrapped">
<p class="error">
ERROR: {this.state.error || 'unknown'}
</p>
</div>
}
{this.state.data &&
<WrappedComponent
{...this.props}
{...this.state.data} />
}
</div>
);
}
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment