Debouncing Asynchronous Validation Requests
Showcase how to debounce asynchronous validation in TanStack Form to avoid flooding the server with requests on every keystroke.
import { useForm, useField } from '@tanstack/react-form';
import { debounce } from 'lodash';
const asyncUsernameValidator = async (username) => {
// Simulate API call
const response = await fetch(`/api/validate-username?username=${username}`);
const { isValid } = await response.json();
if (!isValid) {
return 'Username is already taken';
}
return false;
};
const debouncedAsyncValidation = debounce(asyncUsernameValidator, 500);
This piece of code imports necessary hooks from TanStack Form and the debounce function from lodash. It defines an async function 'asyncUsernameValidator' that simulates an API call to validate a username. The 'debouncedAsyncValidation' is a debounced version of the validator, set with a 500ms delay to prevent spamming the server on every keystroke.
const UsernameField = () => {
const { getInputProps } = useField({
name: 'username',
validate: async (value) => {
const errorMessage = await debouncedAsyncValidation(value);
return errorMessage;
}
});
return <input {...getInputProps()} />;
};
This component uses the 'useField' hook from TanStack Form to create a username input field. The validate function for the field is set to an asynchronous function that calls the debounced validator. This setup ensures that asynchronous validation only occurs after the user has stopped typing for 500ms.