Presupuestador_web/client/src/components/ProtectedRoute/ProtectedRoute.tsx
2024-07-17 13:03:02 +02:00

40 lines
1.1 KiB
TypeScript

import { useGetProfile, useIsLoggedIn } from "@/lib/hooks";
import React, { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Navigate } from "react-router-dom";
import { LoadingOverlay } from "../LoadingOverlay";
type ProctectRouteProps = {
children?: React.ReactNode;
};
export const ProtectedRoute = ({ children }: ProctectRouteProps) => {
const { isPending, isSuccess, data: { authenticated, redirectTo } = {} } = useIsLoggedIn();
const { data: profile, ...profileStatus } = useGetProfile();
const { i18n } = useTranslation();
useEffect(() => {
if (profileStatus.isSuccess && i18n.language !== profile?.lang_code) {
i18n.changeLanguage(profile?.lang_code);
}
}, [profile, profileStatus, i18n]);
if (isPending || profileStatus.isPending) {
return <LoadingOverlay />;
}
if (isSuccess && !authenticated) {
return (
<Navigate
to={redirectTo ?? "/login"}
replace
state={{
error: "No authentication, please complete the login process.",
}}
/>
);
}
return <>{children ?? null}</>;
};