0

I understand how to use hooks, but I'm struggling to convert this function which was in a class component to an asynchronous function that would be featured in a functional component.

//COE LEADING UP TO THE PROBLEM
const [email, setEmail] = useState('')
const [errors, setErrors] = useState({ cognito: null, blankfield: false })

function clearErrorState() {
  setErrors({ cognito: null, blankfield: false })
}

//PROBLEM FUNCTION
forgotPasswordHandler = async event => {
  event.preventDefault()

  // Form validation
  this.clearErrorState()
  const error = ValidateForm(event, this.state)
  if (error) {
    this.setState({
      errors: { ...this.state.errors, ...error }
    })
  }

  // AWS Cognito integration here
  try {
    await Auth.forgotPassword(this.state.email)
    this.props.history.push('/forgotpasswordverification')
  } catch (error) {
    console.log(error)
  }
}

The forgotPasswordHandler in particular is the primary function that I'm having a difficult time converting. I believe that I have it halfway converted. Here's what I think it should be:

async function forgotPasswordHandler(event) {
  event.preventDefault()
  // Form validation
  clearErrorState()
  const error = ValidateForm(event, { email, errors })
  if (error) {
    setErrors({ ...errors, ...error })
  }

  // AWS Cognito integration here
  try {
    await Auth.forgotPassword(email)
    props.history.push('/forgotpasswordverification')
  } catch (error) {
    console.log(error)
  }

  return null
}

This works whenever I submit an email that exists in the database, but it doesn't display any error message in the case of inputting an email that doesn't exist inside of the database. I think I'm doing something wrong with the way I'm using the spread operator in my setErrors method, but I'm not sure how to fix it 100%. If anyone can point out what I'm doing wrong it would be greatly appreciated. Thank you

Andrew J Winkler
  • 465
  • 1
  • 4
  • 14
  • Does this question/answer solve your problem https://stackoverflow.com/questions/49491393/using-spread-operator-to-update-an-object-value ? – noob_nerd Feb 28 '21 at 06:31

1 Answers1

0

state updates in functional components are affected by closure and hence you do not have the updated state in the same call of the function. You can make use of functional approach to set error state

async function forgotPasswordHandler(event) {
  event.preventDefault()
  // Form validation
  clearErrorState()
  const error = ValidateForm(event, { email, errors })
  if (error) {
    // Update state in this manner
    setErrors(prevErrors => ({ ...prevErrors, ...error }));
  }

  // AWS Cognito integration here
  try {
    await Auth.forgotPassword(email)
    props.history.push('/forgotpasswordverification')
  } catch (error) {
    console.log(error)
  }

  return null
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400