0Pricing
React Native Academy · Lesson

Submitting and Resetting Forms

Handle form submission with handleSubmit, make an API call with the validated values, display a success or server-side error message, and reset the form on success.

The handleSubmit Wrapper

handleSubmit from useForm is a higher-order function that wraps your submit handler. When called, it first runs all validation rules. If every field passes, it calls your handler with the typed form data. If any field fails, it populates formState.errors and does not call your handler. Never read form values directly from state inside the submit handler — always use the typed data argument that handleSubmit provides.

const { handleSubmit } = useForm<LoginForm>();

async function onSubmit(data: LoginForm) {
  // data is fully typed — guaranteed to have passed validation
  console.log(data.email, data.password);
  await authApi.login(data.email, data.password);
}

// Wire to button:
<Button title='Log In' onPress={handleSubmit(onSubmit)} />

Making an API Call in the Submit Handler

The submit handler is an async function — handleSubmit handles the Promise automatically. Make your API call inside a try-catch block. On success, navigate to the next screen or show a success message. On failure, use setError to show a field-level error or display a general error with Alert.

async function onSubmit(data: RegisterForm) {
  try {
    await api.register({
      email: data.email,
      password: data.password,
      name: data.name,
    });
    navigation.replace('Home');
  } catch (err: any) {
    if (err.status === 409) {
      setError('email', { message: 'This email is already in use.' });
    } else {
      Alert.alert('Registration Failed', 'Please try again later.');
    }
  }
}

All lessons in this course

  1. Setting Up react-hook-form with Controller
  2. Validation Rules and Error Messages
  3. Multi-Step Forms with Form State
  4. Submitting and Resetting Forms
← Back to React Native Academy