Add download for orders
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
// imports
|
||||
|
||||
import { API_ENDPOINTS } from "~/constants";
|
||||
import { useQuery } from "@tanstack/vue-query";
|
||||
|
||||
const useDownloadInvoice = (transactionId: string) => {
|
||||
// state
|
||||
|
||||
const { $queryClient: queryClient, $axios: axios } = useNuxtApp();
|
||||
|
||||
const enabled = ref(false);
|
||||
|
||||
// methods
|
||||
|
||||
const download = () => {
|
||||
if (!enabled.value) enabled.value = true;
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["download-invoice", transactionId],
|
||||
});
|
||||
};
|
||||
|
||||
// query
|
||||
|
||||
const handleDownloadInvoice = async () => {
|
||||
const { data } = await axios.get<Blob>(`${API_ENDPOINTS.orders.cart.download_invoice}/${transactionId}`, {
|
||||
responseType: "blob",
|
||||
});
|
||||
return data;
|
||||
};
|
||||
|
||||
const { data: file, isLoading } = useQuery({
|
||||
queryKey: ["download-invoice", transactionId],
|
||||
queryFn: () => handleDownloadInvoice(),
|
||||
enabled,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
// watch
|
||||
|
||||
whenever(file, () => {
|
||||
if (!!file.value) {
|
||||
const url = URL.createObjectURL(file.value);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "invoice.pdf";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
enabled.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
downloadIsLoading: isLoading,
|
||||
downloadFn: download,
|
||||
};
|
||||
};
|
||||
|
||||
export default useDownloadInvoice;
|
||||
Reference in New Issue
Block a user