Blog>
Snippets

Implementing Debounced Asynchronous Validation

Illustrate the implementation of debounced asynchronous validation in TanStack Form to enhance UX by reducing unnecessary server validations.
import { useDebounce } from 'use-debounce';
import { useForm, useField } from '@tanstack/react-form';
Import necessary hooks from use-debounce for debouncing functionality and @tanstack/react-form for form management.
const validateUsernameAsync = async (username) => {
  // Simulate an API call
  const isTaken = await fakeApiCheckUsername(username);
  if (isTaken) return 'Username is already taken';
  return true;
};
Define an asynchronous function to validate the username by simulating a server-side check (e.g., to see if the username is already taken).
const MyForm = () => {
  const [debouncedValue] = useDebounce(field.value, 500);
  const form = useForm({
    initialValues: { username: '' },
    onSubmit: async (values) => {
      // Handle form submission
    }
  });

  const field = useField('username', form, {
    validate: async (value) => {
      if (!value) return 'Username is required';
      return validateUsernameAsync(value);
    }
  });

  useEffect(() => {
    field.runValidation();
  }, [debouncedValue]);

  return (
    // Form JSX with input for username
  );
};
Implements the form component using TanStack Form hooks. It includes a debounced asynchronous validation for the username field to minimize unnecessary server validations and enhance user experience by only triggering validation after a specified delay (500ms in this example).