UserDashboard/hoc/withAuth.tsx
2025-02-26 18:00:01 +08:00

28 lines
745 B
TypeScript

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
const withAuth = (WrappedComponent: React.FC) => {
return (props: any) => {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const router = useRouter()
useEffect(() => {
const token = localStorage.getItem("token")
if (!token) {
router.replace("/login") // Redirect to login if no token
} else {
setIsAuthenticated(true)
}
}, [])
if (!isAuthenticated) {
return null // Avoid rendering until auth check is done
}
return <WrappedComponent {...props} />
};
};
export default withAuth