Home > front end >  JWT gets cleared when loading page
JWT gets cleared when loading page

Time:07-12

I am currently working on a project in react with registration and login, and am using JWT for authentication. It works well for the most part; the jwt gets stored in localStorage when the user is logged in. The issue comes when I introduce a button to log out.

<Link to="/">
    <button onClick={localStorage.clear()} style={{backgroundColor: "black"}} className="login-button">Log Out</button>
 </Link>

This log out button is rendered as soon as the user logs in, and I would expect it to clear local storage and return the user to the home page when clicking it. However, when putting localStorage.clear() in the onClick, the JWT token is cleared as soon as the user is logged in, even if the user hasn't clicked on log out. I have found after testing it that this is the code that seems to be the issue, and I can't really see why.

CodePudding user response:

React is executing localStorage.clear() on load because you're not giving a function to the onClick event but rather the execution/call of a function.

Try it this way:

<button onClick={() => {localStorage.clear()}} style={{backgroundColor: "black"}} className="login-button">Log Out</button>

CodePudding user response:

when the page loads the button onClick will get triggered.

<Link to="/">
<button onClick={localStorage.clear} style={{backgroundColor: "black"}} className="login-button">Log Out</button>

this should resolve the issue

  • Related