I want the navigation bar to conditionally show 'login'or 'logout' based on if there is a token stored in local storage. I have it sort of working, but sometimes there is a delay, like I clear the token on logout but the navbar does not update until I refresh the page. I tried adding a context variable that stores a boolean value to keep track of loginStatus. I'm not sure if this is the best way? I'm still seeing that the component sometimes doesn't update until I refresh the page.
export default function Nav() {
const { loginStatus } = useContext(AuthContext)
const navOptions = useLoginStatus()
//useEffect(() => {}, [loginStatus]) ?? can I do this to force the nav component to update when the loginStatus context variable changes?
return (
<nav className="Nav">
<Link to="/">
<span className="logo">
{' '}
AskifyLogo
</span>
</Link>
<div className="profile-tools">
{navOptions}
</div>
</nav>
)
}
function useLoginStatus() {
const { updateLoginStatus } = useContext(AuthContext)
const handleLogoutClick = () => {
updateLoginStatus(false)
TokenService.clearAuthToken()
}
const renderLogoutLink = () => (
<div className='Nav__logged-in'>
<Link
onClick={handleLogoutClick}
to='/'>
Logout
</Link>
</div>
);
const renderLoginLink = () => (
<div className='Nav__not-logged-in'>
<Link to='/register'>
Register
</Link>
<Hyph />
<Link to="/login">
Log in
</Link>
</div>
);
return TokenService.hasAuthToken() ? renderLogoutLink() : renderLoginLink()
}