我正在編寫一個鉤子來從下一個 js 中的即時資料庫取得 userole,我收到錯誤「無法讀取未定義的屬性(讀取'_repo')」。這是我的鉤子的樣子
import { useEffect, useState } from "react"; import { useRouter } 從 "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 的新手。
提供給
onAuthStateChanged()
的回调> 透過User
物件。它沒有role
屬性。這表示以下幾行沒有任何作用:
執行上面的程式碼後,
nodeRef
將變為undefined
,然後您將其輸入到onValue
中,它會引發您看到的錯誤。 p>如果使用者的角色已作為自訂新增至使用者的驗證令牌中宣告,您需要取得使用者的 ID 令牌,然後取得所需的宣告。