0

I have a problem with read a cookie in my browser.. here's my code

const dataA = authService.isLogin();

useEffect(() => {
  if (dataA) {
     router.push("/");
  }
}, [dataA]); ```

the dataA is get a cookie value from my browser.. but thats not working.. it caused my router.push not redirect to the page

how can i solve it ?
2
  • 1
    Where is the code to read the cookie? Please add that. Commented Mar 28, 2022 at 13:16
  • export function getCookie(cname) { if (typeof document === "undefined") return; let name = cname + "="; let decodedCookie = decodeURIComponent(document.cookie); let ca = decodedCookie.split(";"); for (let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == " ") { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } @SurjeetBhadauriya
    – FarhatDje
    Commented Mar 28, 2022 at 13:23

1 Answer 1

1

You should move dataA into useEffect hook because dataA run in SSR not browser so that can't read cookie from browser. Try like this:

useEffect(() => {
  const dataA = authService.isLogin();
  if (dataA) {
     router.push("/");
  }
}, [dataA]); 
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.