[英]firebase.auth().currentUser is null at page load
I successfully check the user's authentication state with onAuthStateChange observer and redirect the user to the profile page.我成功地使用 onAuthStateChange 观察者检查了用户的身份验证 state 并将用户重定向到个人资料页面。 However, I already want to show some user-specific data on the profile, (eg description).
但是,我已经想在个人资料上显示一些特定于用户的数据(例如描述)。 For that, I need the currentUser object to be initialized and populated, which takes some time (I need uid from there to get some data from firestore).
为此,我需要初始化和填充 currentUser object,这需要一些时间(我需要从那里获取 uid 以从 firestore 获取一些数据)。 Thus, I'm looking for some way to wait until this process finishes successfully.
因此,我正在寻找某种方法来等待此过程成功完成。 I'm trying to use async/await syntax on the profile page, but the result returned is null.
我试图在配置文件页面上使用 async/await 语法,但返回的结果是 null。
For now, I'm using local storage when I want to get the data to the next page.现在,当我想将数据获取到下一页时,我正在使用本地存储。
What could be the best way to wait for the currentUser object to be loaded using async/await syntax?使用异步/等待语法等待 currentUser object 加载的最佳方法是什么? I believe that the reason could be that firebase returns null as the first result and then correct uid - after some auth functionality is loaded.
我相信原因可能是 firebase 返回 null 作为第一个结果,然后更正 uid - 在加载了一些身份验证功能之后。
What you're describing is working as expected.您所描述的正在按预期工作。 If you want code to run only after the user's sign-in state has been restored, it needs to be inside an auth state change listener as shown in the first code snippet in the documentation on getting the currently signed in user :
如果您希望代码仅在用户的登录状态恢复后运行,则它需要位于 auth 状态更改侦听器内,如有关获取当前登录用户的文档中的第一个代码片段所示:
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
// 👈 Your code that needs an active user goes here
} else {
// User is signed out
// ...
}
});
There is no way to use await
here, as onAuthStateChanged
doesn't return a promise, but instead fires each time the user's authentication state changes.此处无法使用
await
,因为onAuthStateChanged
不返回承诺,而是在每次用户的身份验证状态更改时触发。
I created a dedicated hook in React js to handle this:我在 React js 中创建了一个专门的钩子来处理这个问题:
import { useEffect, useState } from "react";
import { User } from "firebase/auth";
import { auth } from "../lib/firebase";
const useAuth = () => {
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
return auth.onAuthStateChanged(user => {
setUser(user);
setIsLoading(false);
});
}, []);
return {
user, isLoading
};
}
export default useAuth;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.