Rtk Query Download ^hot^ File -
Once you have the Blob , you need to trigger the browser's download dialog using a temporary link and URL.createObjectURL() . typescript
If the download requires a POST request (e.g., sending a complex filter object), use builder.mutation instead of builder.query .
Always use window.URL.revokeObjectURL(url) to free up memory after the download is initiated. rtk query download file
Standard RTK Query does not natively expose download progress (percentage). For very large files, a direct fetch or axios call with an onDownloadProgress listener might be more appropriate. How to handle Blob and non-serialisable responses ? #3843
// apiSlice.ts 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}`, // Tells RTK Query NOT to parse as JSON responseHandler: (response) => response.blob(), cache: 'no-cache', // Best practice: avoid caching large blobs }), }), }), }); export const { useLazyDownloadReportQuery } = fileApi; Use code with caution. 2. Create a Download Helper Function Once you have the Blob , you need
to treat the data as a Blob .
Servers often send the filename in the Content-Disposition header. You can access this header within a custom queryFn or by inspecting the meta object in transformResponse . Standard RTK Query does not natively expose download
Using a is often better for downloads because it allows you to trigger the request on a specific action, like a button click.