Blog>
Snippets

Server-side Validation and Error Handling in TanStack Form

Explain how to perform server-side validation with TanStack Form by submitting form data to a backend service and handling server validation errors in the form.
import { useMutation } from 'tanstack/react-query';
First, import useMutation from Tanstack's React Query library to handle asynchronous operations and server-side effects.
import { useForm } from '@tanstack/react-form';
Import useForm from TanStack Form to manage the form states and handle submission.
const form = useForm({
  onSubmit: async (values) => {
    await submitForm(values);
  },
});
Initialize the form using useForm hook, providing an onSubmit function where the form data will be submitted to the backend.
const { mutate, isLoading, error } = useMutation(newForm =>
  fetch('/api/submit', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(newForm),
  }).then(res => res.json())
);
Use useMutation to create a mutation function `mutate` for submitting form data to the backend. Handle loading state with `isLoading` and errors with `error`.
const submitForm = (formData) => {
  mutate(formData, {
    onSuccess: (data) => console.log('Form submitted successfully', data),
    onError: (error) => form.setError('server', { message: error.message })
  });
};
Define the submitForm function which calls the `mutate` function with the form data. Handle successful form submission in onSuccess, and set form-level error in case of server validation error in onError.
if (error) {
  return <div>An error occurred: {error.message}</div>;
}
if (isLoading) {
  return <div>Submitting...</div>;
}
// Render Form with TanStack Form
Before rendering the form, check if there are any errors and display them. Also, handle the loading state by showing a loading message while the form is submitting.