Asynchronous Data Validation
Implement async validation in TanStack Form to check uniqueness of a username by querying an API, illustrating error handling and feedback.
import { useForm, useAsyncValidation } from '@tanstack/react-form';
const checkUsernameUnique = async (username) => {
const response = await fetch(`/api/username-check/${username}`);
const { isUnique } = await response.json();
return isUnique;
};
Defines an asynchronous function to check if the username is unique by making an API call, and imports necessary hooks from TanStack Form.
const asyncUsernameValidator = async (username) => {
if (!username) return;
const isUnique = await checkUsernameUnique(username);
if (!isUnique) return 'Username is already taken';
};
An asynchronous validator function for the username field. It calls the previously defined API function and returns an error message if the username is not unique.
const MyForm = () => {
const { Form, useField } = useForm({
onSubmit: async (values) => console.log(values),
validateAsync: useAsyncValidation({
username: asyncUsernameValidator
})
});
const usernameField = useField('username');
return (
<Form>
<div>
<label>Username</label>
<input {...usernameField.getInputProps()} />
{usernameField.error && <p>{usernameField.error}</p>}
</div>
<button type='submit'>Submit</button>
</Form>
);
};
Implements the form using TanStack Form. It uses the asynchronous validator to check the username's uniqueness during form submission and displays any validation errors.