Presupuestador_web/client/src/components/ProtectedRoute/ProtectedRoute.tsx

40 lines
1.1 KiB
TypeScript
Raw Normal View History

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