Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Created January 12, 2018 22:45
Show Gist options
  • Save gabemeola/6ed1308b42fdd948d2b21463dc5f0fa8 to your computer and use it in GitHub Desktop.
Save gabemeola/6ed1308b42fdd948d2b21463dc5f0fa8 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Loading } from 'components';
export default class Enabler extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
/**
* Bootstrap function to run.
* You should wrap this function in a "once()". It will be called on every componentDidMount.
* This function can return either async (Promises) or sync values.
*/
bootstrap: PropTypes.func.isRequired,
}
constructor() {
super();
this.state = {
ready: false,
error: null,
};
}
componentDidMount() {
// Wrapper in Promise.resolve, so we can resolve
// non-Promises in an async manner as well.
Promise.resolve(this.props.bootstrap())
.then(() => {
this.setState({
ready: true,
});
})
.catch((err) => {
console.error('An error occurred while enabling.', err);
this.setState({
err,
});
});
}
render() {
if (this.state.err) return null;
return this.state.ready === true
? this.props.children
: <Loading />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment