score:3

Accepted answer

This is common useState pitfall.

setRegisterErrors([]) works, there's no chance for it to not work because it's called. It triggers synchronous component update. Since onFormSubmit doesn't exit after that, setRegisterErrors(registerErrors.concat(error)) is called after that, where registerErrors is previous state that was defined outside onFormSubmit.

onFormSubmit results in 2 register state updates, where second update (concatenated original array) overrides first update (empty array).

A way to fix this is same as with setState, to use state updater function that provides current state to be updated:

setRegisterErrors(registerErrors => [...registerErrors, error]);

Alternatively, register state updates can be merged:

e.preventDefault();

const registerErrors = [];

setUsername('JDoe');

if( isRegisterFormEmpty(username, email, password, passwordConfirmation) ) {
  registerErrors.push({message: 'Please fill in all fields'});
} else {
  ...
}

setRegisterErrors(registerErrors);

Related Query

More Query from same tag