首页  >  问答  >  正文

Firebase React Hook 错误:无法读取未定义的属性(读取 '_repo')

我正在编写一个钩子来从下一个 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粉436688931P粉436688931236 天前383

全部回复(1)我来回复

  • P粉207969787
  • 取消回复