PrivatePage.tsx 692 B

1234567891011121314151617181920212223242526272829
  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 (
  19. <Spinner />
  20. );
  21. }
  22. return <>{children}</>;
  23. };
  24. export default PrivatePage;