[英]ReactJS: Local Storage taking time to store token, and login page is unable to redirect first time to dashboard route
I am following this procedure:我正在按照这个程序:
- Hitting to Login API
- Getting Success response containing token
- Setting the token to local storage
- Trying to redirect to protected routes
- Protected component check the token from local storage
- For the first time, it is not getting token from local storage as local storage take some time to store token on local storage
- As the token not set yet to local storage, it assumes the use as not authenticated, and then is now redirecting to the login page for the first time.
Moreover, if I keep my token to the state, and then try to check the authentication taking the token from state, then If I logout from one tab or window, then rest of tabs are not logged out automatically.此外,如果我将令牌保存到 state,然后尝试检查从 state 获取令牌的身份验证,那么如果我从一个选项卡或 window 注销,则 rest 个选项卡不会自动注销。 And need to logout from all tabs manually.并且需要手动从所有选项卡注销。
import { Navigate, Route } from "react-router-dom";
import useAuth from "../hooks/useAuth";
const ProtectedRouter = ({ component }) => {
const auth = JSON.parse(localStorage.getItem("token")) ?? false;
if(auth) {
return component;
} else {
return <Navigate replace to="/login"/>
}
};
export default ProtectedRouter;
<Route element={<Layout/>}>
<Route path="/" element={<ProtectedRouter component={<Dashboard/>}/>}/>
</Route>
const login = ({email, password}) => {
axios.post(`http://localhost:7000/api/users/login`, { email, password }).then(response => {
localStorage.setItem("loggedInUser", JSON.stringify(loggedInUser));
localStorage.setItem("token", JSON.stringify(token));
}).catch(err => {
console.error(err.message().toString());
});
};
It has been 3 months since the question was asked, but maybe this can help someone else.自提出问题以来已经 3 个月了,但这也许可以帮助其他人。 I find using navigate('/route-to', { replace: true });
我发现使用navigate('/route-to', { replace: true });
very useful as it refreshes the page making it possible for the token to be available on local storage.非常有用,因为它刷新页面,使令牌可以在本地存储上可用。 I can't see where you are redirecting after a successful login.登录成功后,我看不到你重定向到哪里。 You should redirect like this navigate('/', { replace: true });
你应该像这样重定向navigate('/', { replace: true });
Also, where are you getting the token and loggedInUser from?另外,您从哪里获取令牌和 loggedInUser? After a successful login, the API is returning token, so you should get loggedInUser and token from the response.成功登录后,API 返回令牌,因此您应该从响应中获取 loggedInUser 和令牌。
Here is what you can do.这是您可以做的。
const login = ({email, password, navigate}) => {
axios.post(`http://localhost:7000/api/users/login`, { email, password }).then(response => {
localStorage.setItem("loggedInUser", JSON.stringify(response.data.loggedInUser));
localStorage.setItem("token", JSON.stringify(response.data.token));
navigate('/', { replace: true });
}).catch(err => {
console.error(err.message().toString());
});
};
Dont forget to pass navigate ( useNavigate
) when using login()
.使用login()
时不要忘记传递 navigate ( useNavigate
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.