I have a problem during render a screen in react. I have two modules: login and dashboard. When a user is authenticated and the api's result is 'Ok', I set a localstorage variable 'isLoggedIn' to true and send the user to dashboard screen. Then in dashboard, i checked if this variable is true, and if its ok i show the dashboard, but if the variable is false (cause the user press on the logout button in the dashboard), i set the variable to false and move the user to login screen again.
Everything's ok there, but i need to control if a not logged user try to access to the dashboard by the url (/dashboard), and to restrict that access, i have some conditionals that check if the localstorage variable it's true or false, but always fell in the case if the localstorage 'isloggedIn" is true and I don't know why. I detach the code below.
const Dashboard = () => {
useEffect(() => {
}, [localStorage.getItem('isLoggedIn')]);
return (
<div style={{ alignContent: "center" }}>
{localStorage.getItem('isLoggedIn') && <div><HeaderLogout /> <Content /></div>}
{!localStorage.getItem('isLoggedIn') && <div><HeaderLogin /></div>}
</div>
);
};
export default Dashboard;
CodePudding user response:
The main reason why your conditions will most likely fail is because localStorage
stores values as strings only. This would mean that is storing your isLoggedIn
values as "true" and "false", which will both equate to true (in JS, non-empty strings are seen as truthy).
What you most likely need to do is JSON.parse()
the variable and then check your conditions.
const Dashboard = () => {
useEffect(() => {
}, [localStorage.getItem('isLoggedIn')]); // you can leave this dependency array this way, but it's useless since change in localStorage does not cause rerenders, so the effect won't ever know when the value changes unless some other state change takes place
const isLoggedIn = JSON.parse(localStorage.getItem("isLoggedIn")); // may need to handle additional error handling
return (
<div style={{ alignContent: "center" }}>
{isLoggedIn && <div><HeaderLogout /> <Content /></div>}
{!isLoggedIn && <div><HeaderLogin /></div>}
</div>
);
};
export default Dashboard;
CodePudding user response:
localStorage.getItem('isLoggedIn')
is a string, so also when is "false", in that expression is always true.
If you want to use this like a logical value, you have to declare a variable
let isLoggedIn = JSON.parse(localStorage.getItem('isLoggedIn'))
and then use instead of localStorage.getItem.
Remember to do JSON.stringify()
in the reverse operation