0

I have this code that checks if the user is logged in or not by getting the cookie. So if the cookie is not found then it alerts and navigates the user to the login page.

// trying to get the token
  const tokenExists = Cookies.get('auth-token')
  
  // if no cookie found then redirect the user to the login route to get their auth-token
  if (!tokenExists) {
    alert('Please log in to continue')
    return <Navigate to='/login' />
  }

but when this code gets executed, it alerts two times saying "Please log in to continue" and then redirects the user to the login page when there is only 1 alert call. I'm not sure what is wrong.

dipansh
  • 331
  • 3
  • 15
  • 2
    Render functions shouldn't have side effects (like alerts); that sort of thing should be done in effect hooks. – Quentin Feb 27 '22 at 08:38
  • 1
    Are you using `StrictMode`? If so, everything is rendered twice in development mode (so side effects like `alert` will happen twice), in order to help detect bugs. See https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects – Lionel Rowe Feb 27 '22 at 08:46

0 Answers0