I am creating an application where the login button will disappear/reappear upon logging in. However, the page doesn't update with the new classnames. This is my code so far:
useEffect(() => {
try{
//If token called logged in exists
const loggedin = localStorage.getItem("Logged In")
if (loggedin !== null) {
// Change display style
document.getElementById("pfp").style.display = "block"
document.getElementById("NavLoginButtonpfp").style.display = "block"
} else {
//Keep Original
}
} catch(ErrorResponse) {
console.log(ErrorResponse)
}
},[]);
Ive tried window.location.reload but that just constantly looped. I have added a second parameter to the useEffect but it still loops.
I know its probably a stupid easy question but everywhere i've looked has just told me to add a second parameter
Hello I found this answer that relates to this question and will help you if you decide to keep using document.getElementById
, (Why is document.getElementById() returning null when there is an element with that Id?).
I would advise as I commented which is:
I prefer not using selectors in my react application have you tried creating a toggle and then rendering the content that should be shown / hidden based on that toggle value something like
const [loggedInToggle, setLoggedInToggle] = useState(false);
useEffect(() => {
const loggedin = localStorage.getItem("Logged In")
setLoggedInToggle(loggedin !== null);
},[]);
return (
<div>
{loggedInToggle ? /* content when logged in */ : /* content when not logged in */ }
</div>
);