0

Here I've created a custom hook and i'm trying to refresh the auth token and setting the isAuthenticated state to true once this request is complete.

const useAuth = () => {
    const [isAuthenticated, setIsAuthenticated] = useState();

    const auth = useSelector((state) => state.auth);
    const { exp } = auth;


    useEffect(() => {
        if (auth?.token) {
            const isTokenExpired = (exp) => {
                const currentTime = Date.now() / 1000;
                return exp < currentTime;
            };
            if (isTokenExpired(exp)) {
                console.log("Token is invalid. Refreshing token");
                axios
                    .get("http://localhost:5001/api/auth/refresh", { withCredentials: true })
                    .then(({ data }) => {
                        localStorage.setItem("token", data.accessToken);
                        setIsAuthenticated(true);
                        window.location.reload(false);
                    })
                    .catch((err) => console.log(err));
            } else {
                console.log("Token is valid");
                setIsAuthenticated(true);
            }
        } else {
            console.log("User logged out");
            setIsAuthenticated(false);
        }
    }, [isAuthenticated]);

    return { isAuthenticated };
};

isAuthenticated is then being destructured in my private route wrapper for the downstream logic.

const PrivateRoute = () => {
const { isAuthenticated } = useAuth();

return isAuthenticated ? <Outlet /> : <Navigate to={"/auth"} replace />;
};

The problem that I'm facing is that during the time the axios call is completed and isAuthenticated state is set to true, the private route wrapper is already rendered once. Making isAuthenticated undefined and therefore rendering the false case.

What can I do to make this work seamlessly without breaking.

Hrithik Naha
  • 115
  • 8

1 Answers1

0
const PrivateRoute = () => {
  const { isAuthenticated } = useAuth();

  if (isAuthenticated === undefined) return <>loading</>

  return isAuthenticated ? <Outlet /> : <Navigate to={"/auth"} replace />;
};

and remove

window.location.reload(false);
Konrad
  • 21,590
  • 4
  • 28
  • 64