
[英]why auth.currentUser is null on page refresh in Firebase Authetication
[英]Why can't I access auth.currentUser inside of a ternary if statement? React, firebase
我的目标是在用户登录时显示退出按钮,如果没有显示登录按钮。
如果我使用此代码,则可以访问 auth.currentUser:
const JoinCard = () => {
const auth = getAuth(app);
const [user] = useAuthState(auth);
const usersRef = collection(db, "users");
const signInWithGoogle = async (e) => {
e.preventDefault();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
console.log(result);
console.log(auth.currentUser);
})
.catch((error) => {
console.log(error);
});
const { uid, photoURL, displayName } = auth.currentUser;
await addDoc(usersRef, {
uid: uid,
photoURL: photoURL,
displayName: displayName,
});
};
return (
<div className="w-[85vw] h-[30vh] m-2 rounded-2xl drop-shadow-xl flex justify-center items-center p-2 bg-white/75">
<button className="sign-in" onClick={signInWithGoogle}>
Sign in with Google
</button>
</div>
);
};
function SignOut() {
return (
auth.currentUser && (
<button className="sign-out" onClick={() => auth.signOut()}>
Sign Out
</button>
)
);
}
export default JoinCard;
但是,如果我将 SignIn 按钮放在三元组中,则 auth.currentUser 现在为空。 这是为什么?
return (
<div className="w-[85vw] h-[30vh] m-2 rounded-2xl drop-shadow-xl flex justify-center items-center p-2 bg-white/75">
{user ? (
<SignOut />
) : (
<button className="sign-in" onClick={signInWithGoogle}>
Sign in with Google
</button>
)}
</div>
);
};
);
Firebase 在大多数浏览器环境中自动保留用户凭据,并在页面/应用重新加载时恢复它们。 然而,这要求它调用服务器,以检查帐户是否被禁用。 这意味着在初始加载时currentUser
变量将为null
,因为对服务器的(异步)调用尚未完成。
useAuthState
挂钩包装了一个身份验证状态侦听器,您可以在有关获取当前用户的文档的第一个代码片段中看到该侦听器。 这种结构确保您的代码可以响应身份验证状态的变化,这与 ReactJS 的反应性质完美契合。
因此,如果您想确保您的应用程序显示当前用户状态,请确保始终响应useAuthState
挂钩 - 或直接使用身份验证状态更改侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.