简体   繁体   English

Firebase onAuthStateChanged 总是返回 undefined

[英]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.我一直在尝试创建一个 util 方法,该方法将返回用户对象或用户对象是否存在。 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.如果没有参数,它应该返回一个布尔值,而参数“getUser”应该返回用户对象,但它总是返回未定义。 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.您的return true将一个值返回给onAuthStateChanged ,这就是您的回调。 The onAuthStateChanged is not doing anything with that value. onAuthStateChanged没有对该值执行任何操作。

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 :或者在使用async / await

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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