Replies: 2 comments 3 replies
-
I think it's probably not the best idea to put a whole file into your redux state, especially when it might stay in the cache for a while. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Came across the same problem today and was able to solve it as follows for an Excel export: // api.export.js
import { api } from './api';
const getFileNameFromContentDisposition = (contentDisposition) => {
if (!contentDisposition) {
return 'export';
}
const fileNameIndex = contentDisposition.indexOf('filename="') + 'filename="'.length;
if (!fileNameIndex) {
return 'export';
}
return contentDisposition.substring(fileNameIndex, contentDisposition.length - 1);
};
const downloadRtkQueryResult = async ({ meta }) => {
const { response } = meta;
const fileName = getFileNameFromContentDisposition(response.headers.get('content-disposition'));
const arrayBuffer = await response.arrayBuffer();
const blob = new Blob([arrayBuffer], { type: response.headers.get('content-type') });
saveAs(blob, fileName);
};
const exportApi = api.injectEndpoints({
endpoints: (builder) => ({
getExport: builder.query({
async queryFn({ params }, _queryApi, _extraOptions, fetchWithBQ) {
const result = await fetchWithBQ({
url: 'export',
params: params,
method: 'GET',
headers: {
Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
},
responseHandler: () => {}, // skips serialization
});
downloadRtkQueryResult(result);
return result;
},
}),
}),
});
export const { useLazyGetExportQuery } = exportApi; // ButtonExport.js
...
import { useLazyGetExportQuery } from '../services/api.export';
export const ButtonExport = () => {
const [getExport, { isFetching }] = useLazyGetExportQuery();
return (
<Button
loading={isFetching}
onClick={() => {
getExport({ params: { foo: 'bar' } });
}}
>
Export Excel File
</Button>
);
}; |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I'm converting a small application from Thunks to RTK query. I have one route left, a file download.
I'm using file-saver to perform the final "show the dialog" operation. Here are the guts of my thunk.
I'm wondering if anyone has done this before and has good ideas on what should be returned from the operation, if anything. Where should
saveAs
be called?Also, it would not be the end of the world to leave this as a Thunk.. just a bit inconsistent for future developers.
Beta Was this translation helpful? Give feedback.
All reactions