Using fetch I can create a download link by doing the following code
const result = await fetch(authLinkProps.url, {
headers: {
Authorization: getUserToken(),
},
});
const blob = await result.blob();
const href = window.URL.createObjectURL(blob);
All works fine but I'm using React Query for my project so I want to be consistent and use this to do the same thing.
If I do the following
const { data, error } = useDocuments(authLinkProps.url);
let href: string = '';
console.log(data);
if (data !== undefined) {
href = window.URL.createObjectURL(data);
}
Where useDocuments is
return useQuery<Blob, Error>('document-download', async () => {
const dwnldHeader = {
headers: {
Authorization: currentUser,
responseType: 'blob',
},
};
const { data } = await axios.get<Blob>(apiUrl, dwnldHeader);
return data;
});
I get the error
"Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed."
Data looks like a blob if I console it out?
Any ideas?
useQuery seems to convert blob responses to Strings. What worked for me was to use arraybuffer return type instead and then convert that to blob.
Furthermore the responseType is not part of the headers object, but of the configuration.
In your case for the useDocuments
return useQuery<Blob, Error>('document-download', async (apiUrl) => {
const config = {
headers: {
Authorization: currentUser,
},
responseType: 'blob',
};
const { data } = await axios.get(apiUrl, config);
return new Blob(data);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With