Firebase React Hook 错误:无法读取未定义的属性(读取 '_repo')
P粉436688931
P粉436688931 2024-03-20 12:15:03
0
1
350

我正在编写一个钩子来从下一个 js 中的实时数据库获取 userole,我收到错误“无法读取未定义的属性(读取'_repo')”。这是我的钩子的样子

import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { onAuthStateChanged } from "firebase/auth";
import { auth, db } from "../firebase";

const useAuth = () => {
  const [currentUser, setCurrentUser] = useState(null);
  const [role, setRole] = useState(null);
  const router = useRouter();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        setCurrentUser(user);
        state
      

        
        let nodeRef;
        if (user.role === "user") {
          nodeRef = ref(db, `users/${user.uid}/role`);
        } else if (user.role === "trainer") {
          nodeRef = ref(db, `trainers/${user.uid}/role`);
        } else if (user.role === "admin") {
          nodeRef = ref(db, `admins/${user.uid}/role`);
        } else if (user.role === "nutritionist") {
          nodeRef = ref(db, `nutritionists/${user.uid}/role`);
        }

        onValue(nodeRef, (snapshot) => {
          const userRole = snapshot.val();
          setRole(userRole);
        });
      } else {
        setCurrentUser(null);
        setRole(null);
        // Redirect to login page if user is not logged in
        router.push("/login");
      }
    });

    
    return () => unsubscribe();
  }, []);

  return { currentUser, role };
};

export default useAuth;

这就是我的 firebase 配置的样子

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";
import { getStorage } from "firebase/storage";

const firebaseConfig = {
  
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getDatabase(app);
const storage = getStorage(app);

export { auth, db, storage };

这是我的数据库结构

- users
  - <user_id>
    - displayName: "User's display name"
    - email: "User's email address"
    - role: "user"
    - ...
- trainers
  - <trainer_id>
    - displayName: "Trainer's display name"
    - email: "Trainer's email address"
    - role: "trainer"
    - ...
- admins
  - <admin_id>
    - displayName: "Admin's display name"
    - email: "Admin's email address"
    - role: "admin"
    - ...
- nutritionists
  - <nutritionist_id>
    - displayName: "Nutritionist's display name"
    - email: "Nutritionist's email address"
    - role: "nutritionist"
    - ...

我一直在尝试这个,因为很明显我在数据库上做错了什么,但我尝试阅读文档但仍然遇到问题。我是 firebase 的新手。

P粉436688931
P粉436688931

全部回复(1)
P粉207969787

提供给 onAuthStateChanged()的回调> 通过 User 对象。它没有 role 属性。

这意味着以下几行没有任何作用:

let nodeRef;
if (user.role === "user") {
  nodeRef = ref(db, `users/${user.uid}/role`);
} else if (user.role === "trainer") {
  nodeRef = ref(db, `trainers/${user.uid}/role`);
} else if (user.role === "admin") {
  nodeRef = ref(db, `admins/${user.uid}/role`);
} else if (user.role === "nutritionist") {
  nodeRef = ref(db, `nutritionists/${user.uid}/role`);
}

执行上面的代码后,nodeRef 将变为 undefined,然后您将其输入到 onValue 中,它会引发您看到的错误。 p>

如果用户的角色已作为自定义添加到用户的身份验证令牌中声明,您需要获取用户的 ID 令牌,然后获取所需的声明。

user.getIdTokenResult()
  .then(idToken => {
    const tokenRole = idToken.claims.role;
    // trust it?
    setRole(tokenRole);
  })
  .catch(err => {
    // TODO: Handle token handling errors
  });
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!