I'm writing a hook to get userole from live database in next js and I'm getting error "Cannot read property of undefined (read '_repo')". This is what my hook looks like
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;
This is what my firebase configuration looks like
// 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 };
This is my database structure
- 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" - ...
I've been trying this because it's obvious I'm doing something wrong with the database, but I've tried reading the documentation and still have problems. I am new to firebase.
Provided to
onAuthStateChanged()
的回调> via theUser
object. It has norole
attribute.This means that the following lines have no effect:
After executing the above code,
nodeRef
will becomeundefined
and then you input it intoonValue
and it will throw the error you see . p>If the user's role has been added to the user's authentication token as a custom claim , you need to get the user's ID token and then get the required claims.