Configuring TanStack Form for File Uploads
Demonstrate how to set up a TanStack Form to handle file uploads, including configuration for multipart/form-data.
import { useForm } from '@tanstack/react-form';
import axios from 'axios';
Import the useForm hook from TanStack Form and axios for HTTP requests.
const FileUploadForm = () => {
const { Form, setFieldValue } = useForm({
defaultValues: { file: null },
onSubmit: async (values) => {
const formData = new FormData();
formData.append('file', values.file);
// Replace 'your-upload-endpoint' with your actual upload API endpoint
await axios.post('/your-upload-endpoint', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
});
return (
<Form>
<input
type='file'
onChange={e => setFieldValue('file', e.target.files[0])}
/>
<button type='submit'>Upload File</button>
</Form>
);
};
Defines a FileUploadForm component where a file input is managed by TanStack Form. An onSubmit function handles the file upload by sending it to a server endpoint using FormData and axios.