I have this app, where i want to display an logout button in the navigation when the user is logged in. But for some reason, the button only shows after i do a refresh of the page, not when the user is logged in.
Also the same thing happens for the cart number update (on the same component), it only update the number after a refresh. Here i am trying to get number from local storage. I made a seperat component for the "buy" button since i want it on all items.
I need some help please, what am i doing wrong?
Here is Navigation component:
function Navigation() {
const [loggedIn, setLoggedIn] = useState(JSON.parse(localStorage.getItem("games")));
let history = useHistory();
function logOut() {
localStorage.clear('Email', 'Password');
history.push('/')
}
function getCartItems() {
if (localStorage.getItem("games")) {
return JSON.parse(localStorage.getItem("games")).length
}
else {
return 0;
}
};
return (
<div className="navgation_container">
<div className="navigation_cartcontainer">
<img className="navigation_logo" src={logo} alt="logog bits&bots" />
{loggedIn ? (
<div className="navigation_cartimg">
<img className="navigation_cart" src={cart} alt="cart for the page" />
<p className="navigation_numberitems">{getCartItems()}</p>
<button className="navigation_logout" onClick={logOut}>Log out</button>
</div>
) : (
<div>Test</div>
)}
</div>
</div>
);
}
Using useState might help you and pass in the value from local storage to useState as shown :
useEffect( ()=>{
setLoggedIn(data_from_local_storage);
}[data_from_local_storage]);