I am trying to make an authentication system. Users can sign in and sign out via the top nav bar. The username will store in the local storage. I can find 'user' in my local storage after sign in, and it's gone after signing out.
But it seems that the useEffect doesn't work properly, so the top bar doesn't change accordingly. Any help is appreciated.
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
useEffect(() => {
function checkUserData() {
const user = localStorage.getItem("user");
if (user) {
setIsLoggedIn(true);
}
}
window.addEventListener("storage", checkUserData);
return () => {
window.removeEventListener("storage", checkUserData);
};
}, []);
return (
<Router>
<div className="container">
<TopBar
logout={() => {
localStorage.removeItem("user");
}}
loginStatus={isLoggedIn}
/>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/sign-in/"
element={
<SignIn
toggleLoggedIn={(user) => {
localStorage.setItem("user", user);
}}
/>
}
/>
<Footer />
</div>
</Router>
);
}
function TopBar(props) {
return (
<div>
<AppBar>
<Toolbar >
<Box />
<Box>
{props.loginStatus ? (
<Link
href="/"
onClick={props.logout}
component="button"
>
{"Sign Out"}
</Link>
) : (
<>
<Link
href="/sign-in/"
>
{"Sign In"}
</Link>
<Link
href="/sign-up/"
>
{"Sign Up"}
</Link>
</>
)}
</Box>
</Toolbar>
</AppBar>
<Toolbar />
</div>
);
}
Change logout and toggleLoggedIn functions as below. You need to dispach the storage event, because normally, a storage change is not noticed in the same document that's is making the changes.
() => {
localStorage.removeItem("user");
window.dispatchEvent(new Event("storage"));
}
(user) => {
localStorage.setItem("user", user);
window.dispatchEvent(new Event("storage"));
}
Then change checkUserData as below, to handle the else case, and change isLoggedIn to false.
function checkUserData() {
const user = localStorage.getItem("user");
if (user) {
setIsLoggedIn(true);
}else{
setIsLoggedIn(false);
}
}
And finally change your isLoggedIn definition as below, so you set the login state dynamically according to what's in the storage from previous visit:
const [isLoggedIn, setIsLoggedIn] = useState(localStorage.getItem("user") ? true : false);
You don't change the boolean isLoggedIn. So the navbar don't know when to update.
You have to do something like this :
if (user) {
setIsLoggedIn(true);
} else {
setIsLoggedIn(false);
}
or something on unmount like
useEffect(() => {return () => setIsLoggedIn(false)}, []);
I don't have the context of your application, but the main logic is to pass this boolean to false when user is not loggedin.
Also, I recommend you to externalize this logic via a hook for example "useAuthentication()". So the logic is separated from the render.
Note: The storage event is only triggered when a window other than itself makes the changes.
I found this on https://www.w3schools.com/jsref/event_storage_url.asp