Blog>
Snippets

Handling Server-Side Errors in File Uploads

Provide an example of how to catch and display server-side error messages related to file uploads to the user using TanStack Form.
import { useForm } from '@tanstack/react-form';
import axios from 'axios';

function FileUploadForm() {
  const form = useForm({
    defaultValues: {
      file: null
    },
    onSubmit: async (values) => {
      const formData = new FormData();
      formData.append('file', values.file);
      try {
        // Replace '/api/upload' with your actual API route
        await axios.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        alert('File uploaded successfully');
      } catch (error) {
        form.setError('file', {
          type: 'server',
          message: error.response?.data?.message || 'An error occurred during file upload.'
        });
      }
    }
  });

  return (
    <form onSubmit={form.handleSubmit()}>
      <input
        type="file"
        onChange={(e) => form.setValue('file', e.target.files[0])}
        accept="image/*"
      />
      {form.errors.file && <p>{form.errors.file.message}</p>}
      <button type="submit">Upload</button>
    </form>
  );
}
This block defines a file upload form using TanStack Form. It handles the form submission by posting the file to a server-side API using Axios. If the server returns an error, it catches that error and sets a server type error on the 'file' field using form.setError, displaying the error message to the user.