Guest User

Untitled

a guest
Jan 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3. import { Loading } from 'components';
  4.  
  5.  
  6. export default class Enabler extends Component {
  7. static propTypes = {
  8. children: PropTypes.node.isRequired,
  9. /**
  10. * Bootstrap function to run.
  11. * You should wrap this function in a "once()". It will be called on every componentDidMount.
  12. * This function can return either async (Promises) or sync values.
  13. */
  14. bootstrap: PropTypes.func.isRequired,
  15. }
  16. constructor() {
  17. super();
  18.  
  19. this.state = {
  20. ready: false,
  21. error: null,
  22. };
  23. }
  24. componentDidMount() {
  25. // Wrapper in Promise.resolve, so we can resolve
  26. // non-Promises in an async manner as well.
  27. Promise.resolve(this.props.bootstrap())
  28. .then(() => {
  29. this.setState({
  30. ready: true,
  31. });
  32. })
  33. .catch((err) => {
  34. console.error('An error occurred while enabling.', err);
  35. this.setState({
  36. err,
  37. });
  38. });
  39. }
  40. render() {
  41. if (this.state.err) return null;
  42.  
  43. return this.state.ready === true
  44. ? this.props.children
  45. : <Loading />;
  46. }
  47. }
Add Comment
Please, Sign In to add comment