Skip to content

Instantly share code, notes, and snippets.

@ThisIsMissEm
Created January 9, 2017 13:22
Show Gist options
  • Save ThisIsMissEm/2a1babb16cbd8cd1123576e2c978b20a to your computer and use it in GitHub Desktop.
Save ThisIsMissEm/2a1babb16cbd8cd1123576e2c978b20a to your computer and use it in GitHub Desktop.
const { Children, Component, PropTypes } = require('react')
const hoodieShape = PropTypes.shape({
ready: PropTypes.object.isRequired,
account: PropTypes.object.isRequired,
store: PropTypes.object.isRequired
})
class HoodieProvider extends Component {
constructor(props, context) {
super(props, context);
this.state = {
ready: false,
error: null
};
const hoodie = this.props.hoodie;
hoodie.ready.then(() => {
this.setState({ ready: true });
}, (error) => {
this.setState({ ready: true, error: error });
});
}
getChildContext () {
return {
hoodie: this.props.hoodie
}
}
render () {
const { error, ready } = this.state;
const { children } = this.props
if (!ready) {
return this.props.renderLoading();
}
if (error) {
return this.props.renderError(error);
}
return Children.only(children)
}
}
HoodieProvider.propTypes = {
hoodie: hoodieShape.isRequired,
renderLoading: PropTypes.func.isRequired,
renderError: PropTypes.func.isRequired,
children: PropTypes.element.isRequired
}
HoodieProvider.childContextTypes = {
hoodie: hoodieShape.isRequired
}
HoodieProvider.defaultProps = {
renderLoading: function(){
return <h1>Loading</h1>
},
renderError: function(error) {
return (
<div>
<h1>Error</h1>
<pre>
{error.toString()}
</pre>
</div>
)
}
}
module.exports = HoodieProvider;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment