javascript - 创建用户后 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 仍为空,我不知道为什么?
解决方案
该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 })
推荐阅读
- javascript - 如何从数组创建对象?
- python - 帖子下的评论
- postgresql - 在具有 300 个整数和 300 个字符(20)的表上插入失败
- c# - WPF:如何将窗口的 ShowInTaskbar 属性绑定到代码隐藏值?
- indexing - Power Query: erase row above on certain conditions "_"
- html - 如何指示 HTML 文档是草稿还是存根?
- visual-studio - 检查工作的 C 编译器:“cl.exe - 已跳过”:Visual Studio 2019
- python - 如何按日期时间顺序对作为字符串格式的日期的列名进行排序
- regex - Ruby正则表达式从仅包含一个数字的字符串中提取一个数字并修剪逗号后的部分
- javascript - 使用 alt 属性搜索 img 表并显示整行