Below is the nav bar code I use to enable and disable certain elements. I think the issue is when I first set the sessionStorage key loggedIn it doesn't get updated in the logged variable. How can I fix this? My SessionStorage is updating correctly but my logged value isn't changing. I think I either need to rerun the nav code again or just need to re rerun the
let logged = ....
If someone can help me figure this out it should solve my issue.
function NavBar() {
const navStyle = {
color: 'white',
textDecoration: 'none'
};
// let logged = Boolean;
let logged = sessionStorage.getItem("loggedIn");
let baseTabs = true;
return (
<nav>
<Link style={navStyle} to='/'>
<h3>Aura Flows</h3>
</Link>
<ul className='nav-links'>
{baseTabs && <Link style={navStyle} to='/faq'> <li>FAQ</li> </Link> }
{baseTabs && <Link style={navStyle} to='/pricing'> <li>Pricing</li> </Link> }
{!logged && <Link style={navStyle} to='/login'> <li>Login</li> </Link> }
{!logged && <Link style={navStyle} to='/signup'> <li>Sign Up</li> </Link> }
{logged && <Link style={navStyle} to='/logout'> <li>Logout</li> </Link> }
</ul>
</nav>
);
}
You're on the right track. When the page is loaded, the NavBar
function is run, the session storage is read and the read value is copied into the logged
variable. NavBar
has no way of knowing when the session storage has changed without polling it again.
To fit more with typical React patterns, I would suggest passing the logged-in state as a prop from NavBar
's parent or from wherever the logged in state logic is.
function NavBar(props) {
let logged = props.logged;
...
}
function Parent() {
const [logged, setLogged] = useState(false);
function logIn() {
// Some logic to determine log-in
// Note that you shouldn't depend on front-end code for strong authentication
setLogged(true);
}
return (
<div>
<NavBar logged={logged} />
<button onClick={logIn} />
</div>
);
}
We use the useState
hook to create a state variable. By using the set function that the hook returned, we signal React that something that the view depends on has changed and that it needs to render again.
If you aren't familiar with hooks, check out the React documentation.