Firebase onAuthStateChanged干扰createUserWithEmailAndPassword.then

时间:2019-04-10 23:05:53

标签: javascript firebase firebase-authentication

我正在使用

firebase.auth().createUserWithEmailAndPassword(email, password1)
.then(() => {
        var user_uid = firebase.auth().currentUser.uid;
        db.collection(ll_collection).doc(user_uid).set({
          user_review: 0,
          number_of_reviews: 0
        })
})

它会在创建帐户后立即创建一个以用户ID命名的文档。

我在同一文件上还具有另一个功能,用于检查用户是否已登录:

firebase.auth().onAuthStateChanged(function(user) {
  if(user) {
    setTimeout(function() {
      window.location.href = "/";
    }, 400)                 
  }
})

我必须为此功能设置一个超时时间,因为该帐户是在创建帐户后立即登录的。如果我不设置超时,它将在创建帐户后立即重定向到“ /”而不创建文档。这是有道理的,因为onAuthStateChanged是实时的。

但是还有另一种方法可以在页面上重定向登录用户而不干扰帐户创建后的操作吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

我通常只使用onAuthStateChanged(),而不使用用户创建的then()完成处理程序。

因此,在这种情况下,文档创建和重定向都将在onAuthStateChanged中,您可以在此处进行同步:

firebase.auth().createUserWithEmailAndPassword(email, password1);

firebase.auth().onAuthStateChanged(function(user) {
    if(user) {
        db.collection(ll_collection).doc(user.uid).set({
            user_review: 0,
            number_of_reviews: 0
        }).then(function() {
            window.location.href = "/";
        });
    }
})

如果您只想在新用户时创建文档,则可以检查他们是否已有文档,或拒绝安全规则中的文档(重新)创建。