Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router cannot navigate after Logout without refreshing page

I use the following approach to logout and although there is no error on console and localHistory is cleaned successfully, it cannot navigate to login page without refreshing current page.

const handleLogout = () => {
  localStorage.clear();
  navigate("/login");
};
<Link onClick={() => handleLogout()}>
  <li><span>Logout</span>  </li>
</Link>

I am not sure if there is any need to add route for logout, but I also tried by adding like below:

<Route path="/logout" element={<Login />} />

Any idea?

like image 513
Jack Avatar asked Nov 27 '25 19:11

Jack


1 Answers

The Link is missing a to prop. You can add the missing to prop and then prevent the default link action from occurring so you can issue clearing the localStorage.

Example:

const handleLogout = (e) => {
  e.preventDefault();   // keep link from immediately navigating
  localStorage.clear(); // clear storage
  navigate("/login");   // now navigate away
};

...

<li>
  <Link to="/login" onClick={handleLogout}>
    <span>Logout</span>
  </Link>
</li>

If you don't actually need the link then you can attach the click handler to one of the other DOM elements. Be sure to maintain browser accessibility.

const handleLogout = () => {
  localStorage.clear();
  navigate("/login");
};

...

<li
  role="button"
  tabIndex={0}
  onClick={handleLogout}
  onKeyPress={handleLogout}
>
  <span>Logout</span>
</li>
like image 74
Drew Reese Avatar answered Nov 30 '25 08:11

Drew Reese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!