I'm trying to make a protected route in next JS. I've added a use effect to redirect if no user to the sign-in page
useEffect(() => {
if (!user) {
router.push("/admindashboard");
} else {
return;
}
}, [user]);
the problem is I'm using a custom hook for supabase where I call the user. and when the page loads for some reason it's null then true for the user but because it's null it redirects when it doesn't need to I'm confused about how to prevent this
hook
const { userLoaded, user, signOut, session, userDetails, subscription } =
useUser();
Example page
const newjob = () => {
const { userLoaded, user, signOut, session, userDetails, subscription } =
useUser();
const router = useRouter();
console.log(user, "Session");
useEffect(() => {
if (!user) {
router.push("/dashboard");
} else {
return;
}
}, [user]);
return (
<>
......
</>
);
};
export default newjob;
Inside hook that changes userLoaded
useEffect(() => {
if (user) {
Promise.allSettled([getUserDetails(), getSubscription()]).then(
(results) => {
setUserDetails(results[0].value.data);
setSubscription(results[1].value.data);
setUserLoaded(true);
}
);
}
}, [user]);
CodePudding user response:
You need simply to add isLoading to user then it is simple.
First value of isLoading needs to be true.
useEffect(() => {
if (!isLoading && !user) {
router.push("/admindashboard");
return;
}
return;
}, [user, isLoading]);
CodePudding user response:
if (userLoaded && !user) {
router.push("/admindashboard");
} else {
return;
}
}, [user, userLoaded]);
this should solve the issue.