UserDashboard/hoc/withAuth.tsx
2025-06-03 16:56:25 +08:00

32 lines
711 B
TypeScript

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ComponentType } from "react";
const withAuth = <P extends object>(WrappedComponent: ComponentType<P>) => {
const WithAuthComponent = (props: P) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const router = useRouter();
useEffect(() => {
const token = localStorage.getItem("token");
if (!token) {
router.replace("/login");
} else {
setIsAuthenticated(true);
}
}, []);
if (!isAuthenticated) {
return null;
}
return <WrappedComponent {...props} />;
};
return WithAuthComponent;
};
export default withAuth;