首页 > 解决方案 > 更改电子邮件后重新验证用户 Firebase React

问题描述

我已经建立了一个功能,允许登录用户更新他们的电子邮件。当我更改电子邮件并重定向到其他页面时,显示的电子邮件是旧电子邮件,只有当我刷新页面时才会出现新电子邮件。我相信解决这个问题的最好方法是让系统重新验证用户(我可能错了,我愿意接受建议)。

// UpdateEmail.js

handleSubmit(e) {
  e.preventDefault()

  this.props.updateEmail(this.state.newEmail)

  this.props.history.push('/settings')
}

const mapDispatchToProps = (dispatch) => {
  return {
    updateEmail: (newEmail) => dispatch(updateEmail(newEmail))
  }
}

// authActions.js *NEW*

export const updateEmail = (newEmail, oldEmail, password) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();

    let user = firebase.auth().currentUser
    let credential = firebase.auth.EmailAuthProvider.credential(oldEmail, password);

    user.reauthenticateAndRetrieveDataWithCredential(credential)
      .then(() => {
        user.updateEmail(
          newEmail
        ).then(() => {
          dispatch({ type: 'UPDATE_LOGIN_DETAILS_SUCCESS'})

          firebase.auth().onAuthStateChanged(function(user) {
            if (user) {
              dispatch({
                type: 'CHECK_REAUTH_SUCCESS',
                user: user
              })
            } else {
              dispatch({ type: 'CHECK_REAUTH_ERROR'})
            }
          });
        })
        .catch(err => {
          dispatch({ type: 'UPDATE_LOGIN_DETAILS_ERROR'}, err)
        })
      })
    .catch(err => {
      dispatch({ type: 'REAUTH_ERROR'}, err)
    })
  }
}

// Settings.js this is where the user is redirected after CHECK_REAUTH_SUCCESS

const mapStateToProps = (state) => {
  return {
    licenses: state.firestore.ordered.licenses,
    aircraft: state.firestore.ordered.aircraft,
    profile: state.firebase.profile,
    auth: state.firebase.auth
  }
}

// authActions.js *OLD*

export const updateEmail = (newEmail) => {
  return (dispatch, getState, {getFirebase, getFirestore}) => {
    const firebase = getFirebase();
    const user = firebase.auth().currentUser

    user.updateEmail(
      newEmail
    ).then(() => {
      dispatch({ type: 'UPDATE_LOGIN_EMAIL_SUCCESS'})
    }).catch(err => {
      dispatch({ type: 'UPDATE_LOGIN_EMAIL_ERROR', err })
    })
  }
}

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


推荐阅读