【问题标题】:What is the correct way of handling firebase user creation flow in react-redux application在 react-redux 应用程序中处理 firebase 用户创建流程的正确方法是什么
【发布时间】:2018-11-04 08:04:07
【问题描述】:

我一直在编写我的 React/Rediux/Firebase 应用程序(大约 1 年前开始,但在此期间我有几个月的休息时间 - 所以我可以从时间的角度查看我自己的代码)。 现在我再次检查代码,我有直觉认为它不是最先进的。

我也在使用 Firebase 来管理帐户,在这种情况下是为了创建一个新帐户

我将与创建用户和错误处理相关的所有操作链放在 Actions/index.js 中的一个功能块中。

export const signUpUser = (data) => dispatch => {
  Firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(data.email, data.password)
    .then(response => {
      const userId = Firebase.auth().currentUser()
      getUserInfoRef(userId).set({
        uid: userId,
        isAdmin: false
      })
    })
    .then(response => {
      Firebase.auth().currentUser().updateProfile({
        displayName: `${data.name} ${data.surname}`
      })
    })
    .then(() => {
      dispatch(sendEmailVerification())
    })
    .catch(error => {
      console.log('Error during signUpUser', error)
      dispatch(authError(error))
    })
}

但这是一个好方法吗? 从它的身体发出动作不是某种反模式吗? 也许应该以某种方式拆分(如何?)?

它正在工作,但我对它的外观并不满意 :) 请指教。

【问题讨论】:

    标签: reactjs firebase redux


    【解决方案1】:

    我认为您的代码没有任何问题。只要您将 promise 与 thencatch 块一起使用,它就必须在其中调度。 但是,如果您仍然希望它看起来更好,我建议您像这样使用async/await

    export const signUpUser = (data) => async dispatch => {
      try {
        await Firebase.auth().createUserAndRetrieveDataWithEmailAndPassword(data.email, data.password)
    
        const userId = await Firebase.auth().currentUser()
    
        getUserInfoRef(userId).set({
          uid: userId,
          isAdmin: false
        }) // am not sure if this func is async or not
    
        await Firebase.auth().currentUser().updateProfile({
          displayName: `${data.name} ${data.surname}`
        })
    
        dispatch(sendEmailVerification())
      } catch(e) {
        console.log('Error during signUpUser', error)
        dispatch(authError(error))
      }
    }
    

    PS:很高兴看到 SO 要求人们在这里“好”。我认为这是非常需要的。

    【讨论】:

    • 感谢您的回复@femi-oni 我担心的是这个函数和所有链接完成的工作量。并且动作应该是相当简单的——至少这是我的理解。
    • 啊!是的!行动应该尽可能少。在这种情况下,我建议将其分成两部分:createUserupdateUser(无论如何,您都需要它自己的功能)。因此,如果您在createUserdispatch(updateUser) dispatch 会自动在updateUser 中可用
    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 2023-01-12
    • 2019-09-30
    • 2020-11-11
    • 1970-01-01
    • 2019-07-26
    • 2019-11-22
    • 2010-09-06
    相关资源
    最近更新 更多