Download File With React-query [upd] Guide
This pattern uses Axios to fetch the file as a and then triggers a browser download programmatically. javascript
If you prefer useQuery , perhaps to pre-fetch a file or manage it like other data, you must set enabled: false to prevent it from firing automatically when the component mounts. Download Blob with React Query, createObjectURL error download file with react-query
: Attaching Authorization tokens to the request. This pattern uses Axios to fetch the file
import { useMutation } from '@tanstack/react-query'; import axios from 'axios'; const useDownloadFile = () => { return useMutation({ mutationFn: async ({ fileId, fileName }) => { const response = await axios.get(`/api/files/${fileId}`, { responseType: 'blob', // Critical for binary data headers: { Authorization: `Bearer ${localStorage.getItem('token')}`, }, }); // Create a hidden link and trigger the download const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); // Clean up to prevent memory leaks link.parentNode.removeChild(link); window.URL.revokeObjectURL(url); }, }); }; // Usage in a component const DownloadButton = ({ file }) => { const { mutate, isPending } = useDownloadFile(); return ( mutate({ fileId: file.id, fileName: file.name })} disabled={isPending} > {isPending ? 'Downloading...' : 'Download Report'} ); }; Use code with caution. 2. Alternative: Using useQuery (Lazy Fetching) Alternative: Using useQuery (Lazy Fetching)


