[英]firebase.auth().onAuthStateChanged looping infinitely
I have this code:我有这个代码:
function App() {
const { setUser } = useContext(UserContext);
firebase.auth().onAuthStateChanged((user) => {
console.log("test");
if (user) {
console.log("user");
setUser({ id: user.uid, email: "" });
} else {
console.log("null");
setUser(null);
}
});
return (
<Container>
<Router />
</Container>
);
}
userContext:用户上下文:
const initialState = {
email: null,
id: null,
};
export interface IUserContext {
user: IUser | null;
setUser: React.Dispatch<IUser | null>;
}
export const UserContext = createContext<IUserContext>({
user: initialState,
setUser: () => {},
});
interface IUserContextProvider {
children: JSX.Element;
}
export function UserContextProvider({ children }: IUserContextProvider) {
const [user, setUser] = useState<IUser | null>(initialState);
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
I am trying to set a user object on log in, or log out.我正在尝试在登录或注销时设置用户 object。 The problem is this keeps looping infinitely.
问题是这会无限循环。 How do I stop this from happening?
我该如何阻止这种情况发生? I essentially just want to know when someone is logged in, or logged out.
我本质上只是想知道某人何时登录或注销。
This can be the responsibility of your Provider itself and run inside it's useEffect
like so:-这可能是您的Provider本身的责任,并在它的
useEffect
中运行,如下所示:-
export function UserContextProvider({ children }: IUserContextProvider) {
const [user, setUser] = useState<IUser | null>(initialState);
useEffect(()=>{
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
console.log("test");
if (user) {
console.log("user");
setUser({ id: user.uid, email: "" });
} else {
console.log("null");
setUser(null);
}
});
return unsubscribe;
},[])
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
The onAuthStateChanged
only needs to be registered one-time and so []
dependency array useEffect
is the right place for it. onAuthStateChanged
只需要注册一次,因此[]
依赖数组useEffect
是它的正确位置。 The unsubscribe
will only work when this component unmounts which won't happen for you unless you exit the website. unsubscribe
仅在此组件卸载时才会起作用,除非您退出网站,否则您不会发生这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.