PrivatePage.tsx 678 B

123456789101112131415161718192021222324252627
  1. import { FC, useEffect } from "react";
  2. import { useRouter } from "next/router";
  3. import { useAuth } from "../context/UserContext";
  4. import Spinner from "./Spinner";
  5. const PrivatePage: FC<{ protectedRoutes: string[] }> = ({
  6. protectedRoutes,
  7. children,
  8. }) => {
  9. const { pathname, push } = useRouter();
  10. const { isAuthenticated } = useAuth();
  11. const pathIsProtected = protectedRoutes.includes(pathname);
  12. useEffect(() => {
  13. if (!isAuthenticated && pathIsProtected) {
  14. push("/");
  15. }
  16. }, [isAuthenticated, pathIsProtected, push]);
  17. if (!isAuthenticated && pathIsProtected) {
  18. return <Spinner />;
  19. }
  20. return <>{children}</>;
  21. };
  22. export default PrivatePage;