How To Use Rtk-query Work Download File May 2026

Is your API requiring or a POST request to trigger the download? AI responses may include mistakes. Learn more

: Since RTK Query uses fetch under the hood, your prepareHeaders logic for JWT tokens will work automatically for downloads. how to use rtk-query download file

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; export const fileApi = createApi({ reducerPath: 'fileApi', baseQuery: fetchBaseQuery({ baseUrl: '/api' }), endpoints: (builder) => ({ downloadReport: builder.query({ query: (reportId) => ({ url: `/reports/${reportId}`, method: 'GET', // 💡 Crucial: Tell RTK Query to expect a blob responseHandler: (response) => response.blob(), }), }), }), }); export const { useLazyDownloadReportQuery } = fileApi; Use code with caution. Step 2: Triggering the Download Is your API requiring or a POST request

Often, the server dictates the filename via the Content-Disposition header. To access this, you need to use a custom baseQuery or modify the responseHandler . javascript javascript import { useLazyDownloadReportQuery } from '

import { useLazyDownloadReportQuery } from './fileApi'; const DownloadButton = ({ reportId }) => { const [trigger, { isFetching }] = useLazyDownloadReportQuery(); const handleDownload = async () => { try { const blob = await trigger(reportId).unwrap(); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = `report-${reportId}.pdf`; // Set file name document.body.appendChild(link); link.click(); // Cleanup link.remove(); window.URL.revokeObjectURL(url); } catch (error) { console.error('Download failed:', error); } }; return ( {isFetching ? 'Downloading...' : 'Download Report'} ); }; Use code with caution. Handling Filenames from Headers

Handling file downloads in a web application can be tricky, especially when you want to leverage a powerful data-fetching library like RTK Query. While RTK Query is primarily designed for JSON APIs, it is fully capable of managing binary data and triggers for file downloads.

Using a lazy query is usually better for downloads because you typically want the download to start when a user clicks a button, rather than when a component mounts. javascript