Firebase React Hook Error: Cannot read property of undefined (reading '_repo')
P粉436688931
P粉436688931 2024-03-20 12:15:03
0
1
336

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.

P粉436688931
P粉436688931

reply all(1)
P粉207969787

Provided to onAuthStateChanged()的回调> via the User object. It has no role attribute.

This means that the following lines have no effect:

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`);
}

After executing the above code, nodeRef will become undefined and then you input it into onValue 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.

user.getIdTokenResult()
  .then(idToken => {
    const tokenRole = idToken.claims.role;
    // trust it?
    setRole(tokenRole);
  })
  .catch(err => {
    // TODO: Handle token handling errors
  });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!