reactjstypescriptionic-frameworkcapacitorionic-native

Why are my form inputs not updating correctly?


Whenever I hit submit on my login form, the values in the relevant text fields are not present sometimes. I could target my element and use document.addEventListener but this will not compile if I decide to use Ionic Capacitor down the line.

const LoginForm: React.FC = () => {
  const { handleLogin } = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // handleLogin(username, password);
    console.log("Username: ", username);
    console.log("Password: ", password);

    // Sometimes these values are half complete or just straight up empty strings??
  };

  return (
    <IonPage>
      <IonContent className="ion-padding ion-text-center">
        <div className="login-container">
          <h2>Login</h2>
          <form onSubmit={handleSubmit} className="form">
            <IonItem className="form-item">
              <IonLabel position="floating">Username</IonLabel>
              <IonInput
                value={username}
                onIonInput={(e) => setUsername(e.detail.value!)}
                className="form-input"
              />
            </IonItem>
            <IonItem className="form-item">
              <IonLabel position="floating">Password</IonLabel>
              <IonInput
                type="password"
                value={password}
                onIonInput={(e) => setPassword(e.detail.value!)}
                className="form-input"
              />
            </IonItem>
            {error && <IonText color="danger" className="error-text">{error}</IonText>}
            <IonButton expand="full" type="submit" className="submit-button">
              Login
            </IonButton>
          </form>
        </div>
      </IonContent>
    </IonPage>
  );
};

export default LoginForm;

Sometimes either password or username will be correct, empty strings or half-complete. If I fill in the username first and then the password, the password will be an empty string (and vice versa). What is causing this?


Solution

  • Turns out you can just use onIonChange instead of onIonInput for the form. onIonChange triggers every keystroke but onIonInput triggers every time you click off the input field. In cases where the password or username was entered and the submit button was immediately clicked (before clicking off the input fields) the old value of the field was used (a blank string or half-entered string depending on what the user did).