firebase.auth().currentUser 在页面加载时为空

问题描述 投票:0回答:2

我成功使用 onAuthStateChange 观察者检查用户的身份验证状态,并将用户重定向到个人资料页面。但是,我已经想在个人资料上显示一些特定于用户的数据(例如描述)。为此,我需要初始化和填充 currentUser 对象,这需要一些时间(我需要从那里获取 uid 以从 firestore 获取一些数据)。因此,我正在寻找某种方法来等待该过程成功完成。我尝试在个人资料页面上使用 async/await 语法,但返回的结果为 null。

目前,当我想将数据获取到下一页时,我正在使用本地存储。

使用 async/await 语法等待 currentUser 对象加载的最佳方法是什么?我相信原因可能是 firebase 返回 null 作为第一个结果,然后在加载一些身份验证功能后返回正确的 uid。

javascript async-await firebase-authentication
2个回答
1
投票

我在 React 中创建了一个专用的钩子来处理这个问题:

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;

0
投票

您所描述的内容正在按预期工作。如果您希望代码仅在恢复用户的登录状态后运行,则需要将其置于身份验证状态更改侦听器内,如有关获取当前登录用户的文档中的第一个代码片段所示:

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
    // ...
  }
});

这里无法使用

await
,因为
onAuthStateChanged
不会返回承诺,而是在每次用户的身份验证状态更改时触发。

© www.soinside.com 2019 - 2024. All rights reserved.