简体   繁体   中英

Firebase onAuthStateChanged always returning undefined

I've been trying to make a util method which will return either the user object or if the user object exists. With no params it should return a boolean and with the param "getUser" it should return the user object, but it is always returning undefined. This seemed to work for a while, but then I took a break and came back and it was always returning undefined. Code below

import { getAuth, onAuthStateChanged } from "firebase/auth";
export default function checkAuthState(type?:string){
    const auth = getAuth()
    onAuthStateChanged(auth, (user) => {
        if (user) {
            if(!type) return true
            if(type === "getUser") return user
            else return true
        } else {
            if(!type) return false
            else return false
        }
      });
}

Your return true returns a value to onAuthStateChanged , which is what calls your callback. The onAuthStateChanged is not doing anything with that value.

If you want to have a promise that resolves once the initial user state has been restored, you can do that with:

function checkAuthState(type?:string){
  const auth = getAuth()
  return new Promise((resolve, reject) => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        if(!type) resolve(true)
        if(type === "getUser") resolve(user)
        else resolve(true)
      } else {
        if(!type) resolve(false) false
        else resolve(false)
      }
      unsubscribe();
    });
  })
}

And then call it like this:

checkAuthState().then((result) => {
  console.log(result);
})

Or when using async / await :

const result = await checkAuthState();
console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM