Skip to content

Commit

Permalink
feat: add ErrorBoundary and ErrorFallback components
Browse files Browse the repository at this point in the history
  • Loading branch information
Tedzury committed Jan 5, 2024
1 parent e941ce1 commit e77f941
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 1 deletion.
37 changes: 37 additions & 0 deletions src/components/ErrorBoundary/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/* eslint-disable no-console */
import { Component } from 'react';

type MyProps = {
fallback: JSX.Element;
children: JSX.Element;
};

type MyState = {
hasError: boolean;
};

class ErrorBoundary extends Component<MyProps, MyState> {
constructor(props: MyProps) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError() {
return { hasError: true };
}

componentDidCatch(error: unknown, info: React.ErrorInfo) {
console.log(error, info.componentStack);
}

render() {
const { hasError } = this.state;
const { fallback, children } = this.props;
if (hasError) {
return fallback;
}
return children;
}
}

export default ErrorBoundary;
13 changes: 13 additions & 0 deletions src/components/ErrorFallback/ErrorFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const ErrorFallback = () => {
return (
<div className="flex h-[100dvh] w-full items-center justify-center bg-surface">
<div className="mx-6 max-w-[500px] rounded-md bg-surface-container p-6 text-center text-lg text-on-surface">
Somehow something managed to crash our app...
<br />
<br /> We suggest you to reload the page to continue using the app.
</div>
</div>
);
};

export default ErrorFallback;
6 changes: 5 additions & 1 deletion src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import ReactDOM from 'react-dom/client';

import App from '@/app/App';

import ErrorBoundary from './components/ErrorBoundary/ErrorBoundary';
import ErrorFallback from './components/ErrorFallback/ErrorFallback';
import initFirebaseApp from './firebase';

import '@/styles/index.css';
Expand All @@ -14,6 +16,8 @@ initFirebaseApp();

ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
<ErrorBoundary fallback={<ErrorFallback />}>
<App />
</ErrorBoundary>
</React.StrictMode>,
);
2 changes: 2 additions & 0 deletions src/router/router.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHashRouter } from 'react-router-dom';

import ErrorFallback from '@/components/ErrorFallback/ErrorFallback';
import MainLayout from '@/layouts/MainLayout';
import LoginPage from '@/pages/LoginPage';
import SettignsPage from '@/pages/SettingsPage';
Expand All @@ -14,6 +15,7 @@ export const routes = [
{
path: '/',
element: <MainLayout />,
errorElement: <ErrorFallback />,
children: [
{
path: ROUTES.WELCOME_PAGE,
Expand Down

0 comments on commit e77f941

Please sign in to comment.