I'm trying to make a redirect if the user has a token saved in cookies or not, here's my code:
const Secret = () => {
const router = useRouter();
const [token] = useState({
token: cookies.get("token") || null,
});
if (token.token == null || token.token.hasOwnProperty("error")) {
router.push("/login");
} else {
router.push("/");
}
return (
<>
<h1>Secret</h1>
</>
);
};
But I get this error: No router instance found. you should only use "next/router" inside the client side of your app. Anyone knows how to fix it? Thanks!
I think the problem coming from where you put the code in. Your condition is supposed to be happened as the component is mounted, so try this:
React.useEffect(() => {
if (token.token == null || token.token.hasOwnProperty("error")) {
router.push("/login");
} else {
router.push("/");
}
}, [])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.