[英]My Typescript React + Firebase App logs out on refresh
I am initializing a TS React App connected to Firebase with a private route when the user is logged in.当用户登录时,我正在使用私有路由初始化连接到 Firebase 的 TS React 应用程序。
Everything seems to work well until I refresh the page.在我刷新页面之前,一切似乎都运行良好。 When I do that, the app takes me back to the public route which is a login page.
当我这样做时,该应用程序将我带回作为登录页面的公共路线。
I think that the problem could be the initial state of the context which is set to null , but maybe it's a different problem.我认为问题可能是设置为null的上下文的初始 state ,但也许这是一个不同的问题。
Here is the code for my user context:这是我的用户上下文的代码:
import React, { useContext, useState, useEffect } from "react";
import firebase from "firebase/app";
import { auth } from "../firebase";
export const AuthContext = React.createContext<firebase.User | null>(null);
export function useAuth() {
return useContext(AuthContext);
}
export const AuthProvider: React.FC = ({ children }) => {
const [user, setUser] = useState<firebase.User | null>(null);
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((firebaseUser) => {
setUser(firebaseUser);
});
return unsubscribe;
}, []);
return <AuthContext.Provider value={user}>{children}</AuthContext.Provider>;
};
Here is how I created the private route:这是我创建私有路由的方式:
import React, { useContext } from "react";
import { Redirect, Route, RouteProps } from "react-router";
import { AuthContext } from "../contexts/AuthContext";
interface IPrivateRoute extends RouteProps {
component: any;
}
const PrivateRoute = ({ component: Component, ...rest }: IPrivateRoute) => {
const user = useContext(AuthContext);
setTimeout(() => console.log(user), 1000);
return (
<div>
<Route
{...rest}
render={(props) => {
return user ? <Component {...props} /> : <Redirect to="/login" />;
}}>
</Route>
</div>
);
};
export default PrivateRoute;
I will be grateful for all the helpful answers!我将不胜感激所有有用的答案!
I think you need to save the session to stay authenticated.我认为您需要保存 session 以保持身份验证。 Whenever you refresh the page your user state will be null.
每当您刷新页面时,您的用户 state 将是 null。
What worked for me is I used JWT.对我有用的是我使用了 JWT。 https://jwt.io/
https://jwt.io/
After user logs in successfully my server sends the user a token and I save the token in user's cookies.用户登录成功后,我的服务器向用户发送了一个令牌,我将令牌保存在用户的 cookies 中。 For each PrivateRoute the user requests they will send the token back to server for verification.
对于用户请求的每个 PrivateRoute,他们会将令牌发送回服务器进行验证。 If the verification is successful then return the PrivateRoute to them.
如果验证成功,则将 PrivateRoute 返回给他们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.