1

I have an event handler function that updates some state and then makes a conditional based on that same piece of state. Of course the conditional isn't reflecting the updated state. Is there a way to await the state for changes? If not, how do I achieve this?

async function handleClick(event) {
    console.log(values)
    // make sure email is not empty
    if (values.email.length === 0) {
      setErrors({...errors, email: [{msg: "Email can not be empty."}]});
    }
    // make sure password is not empty
    if (values.password.length === 0) {
      setErrors((prev) => ({...prev, password: [{msg: "Password can not be empty."}]}));
    };
    console.log('about to submit: ', errors);
    if (errors.email || errors.password) return;
    console.log('data is clean');
}
Mint
  • 1,013
  • 1
  • 12
  • 29

1 Answers1

2

React state updates are asynchronously processed, but the useState state updater function is completely synchronous and doesn't return a Promise, so it can't be awaited.

You can collect your errors in the handler and issue a single state update.

function handleClick(event) {
  console.log(values);

  const errors = {};

  // make sure email is not empty
  if (values.email.length === 0) {
    errors.email = [{msg: "Email can not be empty."}];
  }

  // make sure password is not empty
  if (!values.password.length) {
    errors.password = [{msg: "Password can not be empty."}];
  };

  console.log('about to submit: ', errors);

  if (Object.keys(errors).length) { // if there are errors
    setErrors(errors);
    return;
  }
  console.log('data is clean');
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181