Created
March 4, 2018 21:18
-
-
Save sobstel/c0624c21d5fdf3172e00b5f77b929622 to your computer and use it in GitHub Desktop.
Loader/loading Higher-Order Component
This file contains 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
// 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