我正在编写一个钩子来从下一个 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粉2079697872024-03-21 11:06:08
提供给 onAuthStateChanged()
通过 User
< 调用/a> 对象。它没有 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 });