Instantly share code, notes, and snippets.

Embed
What would you like to do?
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