Professional Documents
Culture Documents
If Token Is Not Present
If Token Is Not Present
If Token is not Present I want to redirect the page to login but its not
working. When no token is present or logout i want to redirect the page login
[+1] [2]
Sagar Kattel
[2022-06-29 16:37:30]
[
reactjs
mongodb
express
mongoose
web-development-server
]
[ https://stackoverflow.com/questions/72804989/if-token-is-not-present-i-want-to-redirect-the-page-to-
login-but-its-not-working ]
const [user,setUser]=useState(null);
headers:{
},
});
setUser(res.data);
};
useEffect(()=>{
getUser();
},[]);
localStorage.removeItem("token");
navigate("/login");
};
navigate("/login");
return (
<div className="m-5">
<div className="jumbotron">
</div>
</div>
[+1]
[2022-06-29 17:00:57] Meet Majevadiya
You can check this in the useEffect method if the token is there then getuser otherwise navigate to the login page
useEffect(()=>{
if(!localStorage.getItem("token")){
navigate("/login");
}else{
getUser();
},[]);
www.stackprinter.com/export?question=72804989&service=stackoverflow 1/2
12/2/22, 10:52 AM If Token is not Present I want to redirect the page to login but its not working. When no token is present or logout i want to redire…
[0]
[2022-06-29 16:54:52] Christophe Prat
You shouldn't add your if statement outside of a function, as suggests this website
[1]. if statements can only be used
outside of a function for conditional rendering (i.e. when the if statement returns something).
When you want to check
something only once, you should check it inside of useEffect.
For your example, it should be:
useEffect(() => {
getUser()
if(!localStorage.getItem("token")) {
navigate("/login");
}, [])
[1] https://www.codegrepper.com/code-examples/javascript/how+to+run+a+code+just+once+in+react
Thanks alot buddy it works. But it is now taking lots of time to get the name can you please help me with that - Sagar Kattel
This may be due to the fact that getUser() is an async function, and the if statement is not. Meet Majevadiya's solution should work
better, because it fetches the user data only if there is no token. Does his solution solve the problem? - Christophe Prat
2
www.stackprinter.com/export?question=72804989&service=stackoverflow 2/2