'Accessing localstorage.getItem from different component after user is logged in. Currently only returning null once I try to access it
Currently I got user that being signed in and then routed to my main screen. Once in main screen want to determine the user role by looking at the localstorage.getItem.
Currently got my login to work but can't seem to access the localstorage from my main component. Please help.
My login submit button inside my login component look as follow:
Login.js
const handleLogin = (event) =>{
event.preventDefault();
const user ={
"email": email,
"password": password
}
axios.post('http://localhost:5000/staff/login', user)
.then((response)=>{
if(response.data.accessToken){
localStorage.setItem("user", JSON.stringify(response.data))
localStorage.setItem("role",JSON.stringify(response.data.role))
}
const location = window.location.href="/main"
return response.data && location;
});
}
So I want to try and access the localstorage "role" inside my main and got it as follow currently but only returning null:
Main.js
const userRole = JSON.parse(localStorage.getItem("role"));
const [role , setRole] =useState(userRole);
return (
<div>
{role === 'admin' && (
<AddUser/>
)}
{role === "employee" && (
<Employee/>
)
}
</div>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
