From fdc5f6488357fa7a07528f60af0972e5f16d0bef Mon Sep 17 00:00:00 2001 From: Vojtech Simetka Date: Tue, 27 Apr 2021 12:53:44 +0200 Subject: [PATCH] feat: added error boundary for each page so errors don't crash the whole app (#84) --- src/components/ErrorBoundary.tsx | 35 ++++++++++++++++++++++++++++++++ src/layout/Dashboard.tsx | 7 +++++-- 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 src/components/ErrorBoundary.tsx diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..f0c82de --- /dev/null +++ b/src/components/ErrorBoundary.tsx @@ -0,0 +1,35 @@ +import { Component, ErrorInfo, ReactElement } from 'react' + +interface Props { + children: ReactElement +} + +interface State { + error: Error | null +} + +export default class ErrorBoundary extends Component { + constructor(props: Props) { + super(props) + this.state = { error: null } + } + + static getDerivedStateFromError(error: Error): { error: Error } { + // Update state so the next render will show the fallback UI. + return { error } + } + + componentDidCatch(error: Error, errorInfo: ErrorInfo): void { + // You can also log the error to an error reporting service + console.error({ error, errorInfo }) // eslint-disable-line + } + + render(): ReactElement { + if (this.state.error) { + // You can render any custom fallback UI + return

Something went wrong. Error: {this.state.error.message}

+ } + + return this.props.children + } +} diff --git a/src/layout/Dashboard.tsx b/src/layout/Dashboard.tsx index fdea85c..192c6c2 100644 --- a/src/layout/Dashboard.tsx +++ b/src/layout/Dashboard.tsx @@ -1,4 +1,5 @@ -import React, { useState, useEffect, ReactElement } from 'react' +import { useState, useEffect, ReactElement } from 'react' +import ErrorBoundary from '../components/ErrorBoundary' import { createStyles, Theme, makeStyles } from '@material-ui/core/styles' @@ -71,7 +72,9 @@ const Dashboard = (props: Props): ReactElement => {
-
{props.children}
+ +
{props.children}
+
) }