Home > Software design >  Checking the value in sessionStorage during the render in React returns one result only
Checking the value in sessionStorage during the render in React returns one result only

Time:08-06

I am storing the jwt key in localStorage when user logs in and I am trying to determine that if that key exists, then app should render either "Login/Register" or Logout buttons/links. However, the function I wrote basically almost always returns one value and never changes, even if user logs in/logs out. So if my user log-in he still can only see register/login button instead of logout or vice-versa somehow - they never change. What should I change to make it display those links/button like it should be? I even made little button on render to check myself the current value of localStorage or if there's any.

My App.js:

class App extends Component {


render() {

    function logOut() {
        localStorage.removeItem("jwt");
    }

    function isLoggedIn() {

        if (localStorage.hasOwnProperty('jwt')) {
            alert(`${'jwt'}: ${localStorage.getItem('jwt')}`);
            return true;
        } else {
            alert(`${'jwt'}: ${'none'}`);
            return false;
        }
    }


    return (
        <Router>
            <div>
                <div  id="myTopnav">
                    <a href="/" >Home</a>
                    <a href="#about">About</a>
                    <button onClick={isLoggedIn}>Default</button>;

                    {isLoggedIn ? (
                    <a href="/login"  onClick={logOut} >Logout</a>) : (
                    <><a href="/login" >Login</a><a href="/register" >Register</a></>
                    )}

                    <a href="javascript:void(0);"  onClick={myFunction}>
                        <i ></i> </a>

                </div>

My Login.js:

function LoginForm() {

...////
        if (res.status === 200) {
            setEmail("");
            setMessage("Logged in successfully");
            const token = resJson.token;              
            localStorage.setItem("jwt", token);
            invalidLogin = false;
            navigate("/", { replace: true });
        } else .....///

And here's example: when I click the button while there's no jwt in storage, the alert returns that there's none, but the logout link is still displayed. No jwt but theres logout button

CodePudding user response:

Check this part:

{isLoggedIn ? (
  <a href="/login"  onClick={logOut} >Logout</a>) : (
 <><a href="/login" >Login</a><a href="/register" >Register</a></>)}

you declared isLoggedIn as a function, so you need to call it if you want to get the value true or false depending on your logic.

so instead of isLoggedIn, you should call:

{isLoggedIn() ? ( ....
  • Related