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

31 lines
730 B
TypeScript
Raw Normal View History

2024-06-06 11:05:54 +00:00
import { useIsLoggedIn } from "@/lib/hooks";
import React from "react";
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-06-06 11:05:54 +00:00
2024-06-06 21:07:40 +00:00
if (isPending) {
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
};