如何将附加数据传递给向对象添加内容的函数?

How to pass additional data to a function that adds things to an object?

我正在尝试为普通用户和 Firebase 上的商家创建用户配置文件文档。我试图在商家注册时向此文档添加额外的数据,但没有成功。不同之处在于,商家应该有一个包含其角色的 roles 数组。如果这不是处理区分用户的正确方法,我也很乐意听到什么是最佳实践。

我的userService文件

async createUserProfileDocument(user, additionalData) {
    console.log('additionalData: ', additionalData) //always undefined
    if (!user) return
    const userRef = this.firestore.doc(`users/${user.uid}`)
    const snapshot = await userRef.get()
    if (!snapshot.exists) {
      const { displayName, email } = user
      try {
        await userRef.set({
          displayName,
          email,
          ...additionalData,
        })
      } catch (error) {
        console.error('error creating user: ', error)
      }
    }
    return this.getUserDocument(user.uid)
  }

  async getUserDocument(uid) {
    if (!uid) return null
    try {
      const userDocument = await this.firestore.collection('users').doc(uid).get()
      return { uid, ...userDocument.data() }
    } catch (error) {
      console.error('error getting user document: ', error)
    }
  }

这是用户在 RegisterMerchant 组件中注册为商家时发生的情况:

onSubmit={(values, { setSubmitting }) => {
        async function writeToFirebase() {
          //I can't pass the 'roles' array as additionalData
          userService.createUserProfileDocument(values.user, { roles: ['businessOnwer'] })          
          authService.createUserWithEmailAndPassword(values.user.email, values.user.password)
          await merchantsPendingApprovalService.collection().add(values)
        }
        writeToFirebase()

这恐怕与onAuthStateChange有关,可能是上面的运行之前没有通过任何additionalData?这是在 Middleware 中,我控制所有路线。

useEffect(() => {
    authService.onAuthStateChanged(async function (userAuth) {
      if (userAuth) {
        //is the below running before the file above and not passing any additional data?
        const user = await userService.createUserProfileDocument(userAuth) //this should return the already created document?
        //** do logic here depending on whether user is businessOwner or not
        setUserObject(user)
      } else {
        console.log('no one signed in')
      }
    })
  }, [])

onCreate回调函数,在用户通过身份验证时调用。

下面是您可以如何实现它

const onSubmit = (values, { setSubmitting }) => {

  const { user: {email, password} } = values;
  const additionalData = { roles: ['businessOnwer'] };

  auth.user().onCreate((user) => {
      const { uid, displayName, email } = user;

      this.firestore.doc(`users/${uid}`).set({
            displayName,
            email,
            ...additionalData
      });
  });

  authService.createUserWithEmailAndPassword(email, password);
}