Skip to content

Commit

Permalink
Refactor ProtectedRoutes component to include loading state and spinner
Browse files Browse the repository at this point in the history
  • Loading branch information
waveyboym committed Oct 21, 2024
1 parent 620210c commit e6a2b97
Showing 1 changed file with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ReactNode, useEffect } from "react";
import { ReactNode, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import AuthService from "AuthService";
import { useUser } from "userStore"; // Assuming this is your user context or global state
import { Spinner } from "@nextui-org/react";

interface ProtectedRouteProps {
authRoutes: ReactNode;
Expand All @@ -11,6 +12,7 @@ interface ProtectedRouteProps {
const ProtectedRoute = (props: ProtectedRouteProps) => {
const { userDetails, setUserDetails } = useUser(); // Retrieve userDetails from global state
const navigate = useNavigate();
const [loading, setLoading] = useState(true); // Loading state to show a spinner while checking authentication

useEffect(() => {
const checkAuthentication = async () => {
Expand All @@ -23,10 +25,20 @@ const ProtectedRoute = (props: ProtectedRouteProps) => {
setUserDetails(null);
}
}
setLoading(false); // Set loading to false after the check is done
};

checkAuthentication();
}, [navigate]);
}, [navigate, userDetails, setUserDetails]);

if (loading) {
return (
<div className="w-screen h-screen flex flex-col justify-center items-center">
<Spinner size="lg" />
<p className="mt-2 text-text_col">Just a moment...</p>
</div>
)
}

return userDetails ? props.authRoutes : props.unAuthRoutes;
};
Expand Down

0 comments on commit e6a2b97

Please sign in to comment.