Checking the value in sessionStorage during the render in React returns one result only

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() {

    function isLoggedIn() {

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

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

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

                    <a href="javascript:void(0);" class="icon" onClick={myFunction}>
                        <i class="fa fa-bars"></i> </a>


My Login.js:

function LoginForm() {

        if (res.status === 200) {
            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

>Solution :

Check this part:

{isLoggedIn ? (
  <a href="/login" class="split" onClick={logOut} >Logout</a>) : (
 <><a href="/login" class="split">Login</a><a href="/register" class="split">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() ? ( ....

Leave a Reply