aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/util/ErrorBoundary/index.tsx
blob: a37d1b33a81ac8ce3d29643b170c45e78419a8ee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { Component, type ReactNode } from 'react';
import { type IntlShape, defineMessages, injectIntl } from 'react-intl';
import withStyles, { type WithStylesProps } from 'react-jss';

import Button from '../../ui/button';
import { H1 } from '../../ui/headline';

import styles from './styles';

const messages = defineMessages({
  headline: {
    id: 'app.errorHandler.headline',
    defaultMessage: 'Something went wrong.',
  },
  action: {
    id: 'app.errorHandler.action',
    defaultMessage: 'Reload',
  },
});

interface ErrorBoundaryProps extends WithStylesProps<typeof styles> {
  intl: IntlShape;
  children?: React.ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props) {
    super(props);

    this.state = {
      hasError: false,
    };
  }

  componentDidCatch(): void {
    this.setState({ hasError: true });
  }

  render(): ReactNode {
    const { classes, intl } = this.props;

    if (this.state.hasError) {
      return (
        <div className={classes.component}>
          <H1 className={classes.title}>
            {intl.formatMessage(messages.headline)}
          </H1>
          <Button
            label={intl.formatMessage(messages.action)}
            buttonType="inverted"
            onClick={() => window.location.reload()}
          />
        </div>
      );
    }

    return this.props.children;
  }
}

export default withStyles(styles, { injectTheme: true })(
  injectIntl<'intl', ErrorBoundaryProps>(ErrorBoundary),
);