我写了一个钩子来从我的实时数据库中获取userole,在接下来的js中,我得到了错误Cannot read properties of undefined(阅读'_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的新手。
1条答案
按热度按时间huus2vyu1#
提供给
onAuthStateChanged()
的回调通过User
对象调用。它没有role
属性。这意味着下面的行没有任何用处:
在上面的行执行之后,
nodeRef
将是undefined
,然后将其输入到onValue
中,这将抛出您看到的错误。如果用户的角色已经添加到user's authentication token as a custom claim上,您将需要获取用户的ID令牌,然后获取所需的声明。