【问题标题】:How to listen that a user created by firebase createUserWithEmailAndPassword has been written to the firebase database?如何监听由 firebase createUserWithEmailAndPassword 创建的用户已写入 firebase 数据库?
【发布时间】:2021-01-06 06:02:33
【问题描述】:

我正在使用 createUserWithEmailAndPassword 创建用户,并将用户保存到实时 firebase 数据库。创建用户后,我想在数据库中更新此用户数据。

通常的流程是 createUserWithEmailAndPassword 创建一个用户并将其保存到数据库中,然后我更新该用户的数据。

但是,有时通过 createUserWithEmailAndPassword 创建用户但未将其保存在数据库中,首先设置更新,然后 createUserWithEmailAndPassword 将用户保存到数据库,因此它会覆盖更新。

顺便说一句,我使用 async await 来等待 createUserWithEmailAndPassword 返回的 promise 解决,然后开始更新用户。

const res = await secondaryApp.auth().createUserWithEmailAndPassword(user.email, password)
await secondaryApp.auth().signOut();

if (newAvatar) {
  const type = newAvatar.type.slice(6);

  const { blob } = newAvatar;

  const ref = storage.child(`users/${res.user.uid}.${type}`);
  const image = await ref.put(blob);
  const imageUrl = await image.ref.getDownloadURL();

  user.avatar = imageUrl;
  user.thumbnail = imageUrl;
}

await firebase
  .database()
  .ref(`users/${res.user.uid}`).set(
    {
      public: {
        ...user
      }
    }
  ).then(
    firebase.auth().sendPasswordResetEmail(user.email).then(
      done(
        "success",
        "Successfull user creation.",
        `A new user has been created.`
      )
    )
  )

},

【问题讨论】:

    标签: javascript firebase firebase-authentication


    【解决方案1】:

    您应该使用文档中所示的auth state observer 在用户登录时注册回调,无论他们如何设法登录。您可以使用此回调来确保用户的如有必要,会创建记录。

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
      } else {
        // User is signed out.
      }
    });
    

    在创建新用户或刚刚使用现有帐户登录时都会调用观察者。在这两种情况下,您都需要检查您的数据库以确保您的数据库包含正确的信息。

    【讨论】:

    • 实际上我是从管理面板创建用户,所以我不需要他们登录,我只想创建它们并更新那里的数据。我将代码附加到问题中,您可以检查它并理解我的意思。顺便谢谢你。
    • 您显示的代码在应用程序中创建用户帐户。如果您有不同的情况,请编辑问题以解释您实际在做什么。
    猜你喜欢
    • 2017-11-12
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2017-06-16
    • 2021-07-01
    • 2017-03-09
    • 1970-01-01
    相关资源
    最近更新 更多