Files
frontend/src/app/routes/RouteErrorBoundary/RouteErrorBoundary.tsx
T
ksv741 7c28a423dd
Frontend verify / commits (pull_request) Successful in 24s
Frontend verify / security (pull_request) Failing after 9s
Frontend verify / verify (pull_request) Skipped
refactor: tighten types and reuse instrument UI
2026-09-29 06:15:31 +03:00

83 lines
1.9 KiB
TypeScript

import type { FC, PropsWithChildren } from "react";
import { Button, Stack, Text, Title } from "@mantine/core";
import { useDocumentTitle } from "@mantine/hooks";
import { Component } from "react";
import { useTranslation } from "react-i18next";
import { Link, useLocation } from "react-router";
import { useAuth } from "@/features/auth";
type BoundaryProps = PropsWithChildren<{
authenticated: boolean;
routeKey: string;
}>;
type RouteErrorFallbackProps = {
authenticated: boolean;
};
type State = { hasError: boolean };
class Boundary extends Component<BoundaryProps, State> {
static getDerivedStateFromError(): State {
return { hasError: true };
}
override state: State = { hasError: false };
override componentDidUpdate(previousProps: BoundaryProps) {
if (previousProps.routeKey !== this.props.routeKey && this.state.hasError) {
this.setState({ hasError: false });
}
}
override render() {
return this.state.hasError
? <RouteErrorFallback authenticated={this.props.authenticated} />
: (
this.props.children
);
}
}
const RouteErrorFallback: FC<RouteErrorFallbackProps> = (props) => {
const { authenticated } = props;
const { t } = useTranslation();
useDocumentTitle(`${t("routeError.title")} — ${t("appName")}`);
const to = authenticated ? "/accounts" : "/login";
return (
<Stack>
<Title order={1}>{t("routeError.title")}</Title>
<Text>{t("routeError.text")}</Text>
<Button component={Link} to={to}>
{t("routeError.action")}
</Button>
<Button component="a" href={to} variant="default">
{t("routeError.reload")}
</Button>
</Stack>
);
};
const RouteErrorBoundary: FC<PropsWithChildren> = (props) => {
const { children } = props;
const { key, pathname, search } = useLocation();
const { user } = useAuth();
return (
<Boundary
authenticated={Boolean(user)}
routeKey={`${pathname}${search}:${key}`}
>
{children}
</Boundary>
);
};
export { RouteErrorBoundary };