PrivatePage.tsx 744 B

123456789101112131415161718192021222324252627282930
  1. import { FC, useEffect } from "react";
  2. import { useRouter } from "next/router";
  3. import { useAuth } from "../context/UserContext";
  4. const PrivatePage: FC<{ protectedRoutes: string[] }> = ({
  5. protectedRoutes,
  6. children,
  7. }) => {
  8. const { pathname, push } = useRouter();
  9. const { isAuthenticated } = useAuth();
  10. const pathIsProtected = protectedRoutes.includes(pathname);
  11. useEffect(() => {
  12. if (!isAuthenticated && pathIsProtected) {
  13. push("/");
  14. }
  15. }, [isAuthenticated, pathIsProtected, push]);
  16. if (!isAuthenticated && pathIsProtected) {
  17. return (
  18. <div className="form-alert-msg">
  19. There was an error, please reload the page
  20. </div>
  21. );
  22. }
  23. return <>{children}</>;
  24. };
  25. export default PrivatePage;