Blog>
Snippets

Initializing TanStack Form with Async Validation

Demonstrate how to initialize a form using TanStack Form and configure a field with asynchronous validation that checks input against server-side criteria.
import { useForm, useField } from '@tanstack/react-form';
import axios from 'axios';
Imports useForm and useField hooks from TanStack React Form and Axios for making HTTP requests.
const asyncUsernameValidator = async (value) => {
  try {
    const response = await axios.post('/api/username-validate', { username: value });
    if (response.data.isUnique !== true) {
      return 'Username is already taken.';
    }
  } catch (error) {
    return 'Error validating username.';
  }
};
Defines an asynchronous function that validates the uniqueness of the username by making a POST request to the server. It returns an error message if the username is taken or there's an error during validation.
function MyForm() {
  const form = useForm({
    onSubmit: async (values) => {
      // Handle form submission
      console.log(values);
    },
    validate: ({ values, setFieldError }) => {
      if (!values.username) {
        setFieldError('username', 'Username is required');
      }
    }
  });

  const usernameField = useField({
    form,
    name: 'username',
    validate: asyncUsernameValidator,
    validatePolicies: {
      onBlur: true,
      onChange: false
    }
  });

  return (
    <form onSubmit={form.handleSubmit}>
      <input {...usernameField.getInputProps()} />
      {usernameField.error ? <div>{usernameField.error}</div> : null}
      <button type="submit">Submit</button>
    </form>
  );
}
Implements a form component using TanStack Form. It initializes the form and a 'username' field with asynchronous validation using the previously defined asyncUsernameValidator. The validation is triggered onBlur, meaning it will run when the input loses focus. This approach minimizes unnecessary validations and enhances performance.