首页 > 解决方案 > 创建用户后 Firebase v9 auth.currentUser 为空

问题描述

这是我的 JS 代码:

import { ref } from "vue"
import { projectAuth } from '../firebase/config'
import { getAuth, createUserWithEmailAndPassword, updateProfile } from 'firebase/auth'

const error = ref(null)
const isPending = ref(false)

const signup = async(email, password, displayName) => {
    error.value = null
    isPending.value = true

    try {
        const res = createUserWithEmailAndPassword(projectAuth, email, password)
        console.log(projectAuth.currentUser)

        if (!res) {
            console.log('Could not complete the signup')
            throw new Error('Could not complete the signup')
        }

        console.log(projectAuth.currentUser)
        await updateProfile(projectAuth.currentUser, {displayName})        
        error.value = null
        isPending.value = false

        return res
        
    } catch(err) {
        console.log('ERROR: ' + err.message)
        error.value = err.message
        isPending.value = false
    }
}

const useSignup = () => {
    return {error, signup, isPending}
}

export default useSignup

每当用户注册时,我的 Vue3 应用程序都会调用此脚本中的注册函数。createUserWithEmailAndPassword 函数成功,用户出现在 firebase 中。但我还想为我的用户添加一个显示名称,所以我试图使用 updateProfile 函数来做到这一点,但有一个问题。

问题是即使在创建用户之后 projectAuth.currentUser 仍为空,我不知道为什么?

标签: javascriptfirebasefirebase-authentication

解决方案


createUserWithEmailAndPassword()方法返回一个承诺。由于您的功能是async,请尝试添加await

const res = await createUserWithEmailAndPassword(projectAuth, email, password)
console.log(projectAuth.currentUser)

或者,您可以直接从 res传递User对象:updateProfile

const { user } = await createUserWithEmailAndPassword(projectAuth, email, password)

await updateProfile(user, { displayName })

推荐阅读