我正在使用createUserWithEmailAndPassword()方法注册新用户。在这个用户创建过程之后,我立即发送电子邮件验证。然后,在我的onAuthStateChanged()中,我有一个条件来检查用户是否已经验证了他们的电子邮件。问题是,在电子邮件sendEmailVerification()方法完成之前,Auth观察者正在注销用户。
基于以下代码的,哪里是成功取消订阅观察者的最佳位置?另外,如何用Firebase JS SDK v9?来实现?
让我解释一下我的用例并展示我的代码:
pages/sign-up**:**
async signUp() {
const auth = getAuth()
const batch = writeBatch(db)
try {
const UserCredential = await createUserWithEmailAndPassword(
auth,
this.formValues.email,
this.formValues.password
)
const userDocRef = doc(db, 'users', UserCredential.user.uid)
batch.set(userDocRef, {
uid: UserCredential.user.uid,
displayName: this.formValues.displayName,
photoURL: `https://gravatar.com/avatar/${md5(
this.formValues.email
)}?d=identicon`
})
const usernameDocRef = doc(db, 'usernames', this.formValues.displayName)
batch.set(usernameDocRef, { uid: UserCredential.user.uid })
// Commit batch
await batch.commit()
console.log('batch committed, user is:', UserCredential.user.uid)
await this.verifyEmail() // <-- user is logged out before this has a chance to fire!verifyEmail()
async verifyEmail() {
const auth = getAuth()
const actionCodeSettings = {
url: `${this.$config.baseUrl}/email-confirmation/success`
}
try {
await sendEmailVerification(auth.currentUser, actionCodeSettings)
} catch (error) {
console.error('An email verification error happened', error)
this.errorMessage = error.message
}
},在我的onAuthStateChanged()方法中,如果用户的电子邮件尚未被验证,我将立即注销他们。这将导致以下错误:

下面是如何设置我的onAuthStateChanged观察者(它在呈现页面之前运行):
~/plugins/auth.js**:**
onAuthStateChanged(auth, (user) => {
if (user) {
if (!user.emailVerified) {
// User has not verified the email yet
store.dispatch('logOutUser')
}
// TO DO: finish up rest of user logic取消订阅应该在auth.js还是pages/sign-up页面中?我不知道如何取消订阅。
发布于 2021-07-28 15:17:16
如果您需要在注册/登录后执行某些操作,那么您应该从auth观察者那里取消订阅,因为您已经知道了。
const authObserver = onAuthStateChanged(auth, (user) => {
// ...
}
async signUp() {
//unsubscribe here i.e when user clicks signup button
authObserver()
const auth = getAuth()
const batch = writeBatch(db)
// ...
}请注意,如果您的观察者打算将登录用户重定向到其他地方,那么它现在就不会这么做了。所以一定要手动完成。
https://stackoverflow.com/questions/68562934
复制相似问题