export default function Home() {
const [redirect, setRedirect] = useState<boolean>(false);
const [redirecting, setRedirecting] = useState<boolean>(false);
const userContext = useContext(UserContext);
useEffect(() => {
const value: string | null = localStorage.getItem("user");
if (!value) {
return setRedirecting(true);
}
const user: User = JSON.parse(value ?? "");
if (userContext) {
userContext.setUser({
...user,
});
}
}, [userContext]);
useEffect(() => {
if (redirecting) {
setTimeout(() => {
console.log("here 1")
setRedirect(true)
}, 3000);
}
}, [redirecting]);
if (redirecting || !userContext?.user) {
return (
<Container sx={{ my: 2 }}>
<Typography variant="h5">
You need to register to access this page.
</Typography>
</Container>
);
}
if (redirect) {
console.log("here 2");
return <Navigate to={ "/register"} />
}
return (
<div>Home Content</div>
);
}
The value of redirect does get changed, but somehow the code responsible to navigate is not executing.
2
Answers
When you set
redirect
totrue
theredirecting
is stilltrue
, therefore the first condition is true and the first return is the one executing.You should change the logic of the return
first of all simplify your code, also use react best practices. it will help you to debug code easily. something like below.