|
| 1 | +import { showError } from '@Common/Helper' |
| 2 | +import { ToastBody } from '@Common/ToastBody' |
| 3 | +import { useState } from 'react' |
| 4 | +import { toast } from 'react-toastify' |
| 5 | +import { getDownloadResponse } from './service' |
| 6 | + |
| 7 | +export interface HandleDownloadProps { |
| 8 | + downloadUrl: string |
| 9 | + showFilePreparingToast?: boolean |
| 10 | + fileName?: string |
| 11 | +} |
| 12 | + |
| 13 | +const useDownload = () => { |
| 14 | + const [isDownloading, setIsDownloading] = useState<boolean>(false) |
| 15 | + |
| 16 | + /* |
| 17 | + downloadUrl: API url for downloading file |
| 18 | + showFilePreparingToast: Show toast 'Preparing file for download' |
| 19 | + fileName: fileName of the downloaded file |
| 20 | + */ |
| 21 | + const handleDownload = async ({ downloadUrl, showFilePreparingToast = false, fileName = 'file.tgz' }) => { |
| 22 | + setIsDownloading(true) |
| 23 | + if (showFilePreparingToast) { |
| 24 | + toast.info( |
| 25 | + <ToastBody |
| 26 | + title="Preparing file for download" |
| 27 | + subtitle="File will be downloaded when it is available." |
| 28 | + />, |
| 29 | + ) |
| 30 | + } |
| 31 | + try { |
| 32 | + const response = await getDownloadResponse(downloadUrl) |
| 33 | + if (response.status === 200) { |
| 34 | + const data = await (response as any).blob() |
| 35 | + |
| 36 | + // Create a new URL object |
| 37 | + const blobUrl = URL.createObjectURL(data) |
| 38 | + |
| 39 | + // Create a link element |
| 40 | + const a = document.createElement('a') |
| 41 | + a.href = blobUrl |
| 42 | + a.download = fileName |
| 43 | + |
| 44 | + // Append the link element to the DOM |
| 45 | + document.body.appendChild(a) |
| 46 | + |
| 47 | + // Programmatically click the link to start the download |
| 48 | + a.click() |
| 49 | + |
| 50 | + // Clean up the URL object after the download is complete |
| 51 | + setTimeout(() => { |
| 52 | + URL.revokeObjectURL(blobUrl) |
| 53 | + document.body.removeChild(a) |
| 54 | + }, 0) |
| 55 | + |
| 56 | + toast.success('Downloaded Successfully') |
| 57 | + } else { |
| 58 | + const error = (await response.json()).errors[0].userMessage |
| 59 | + showError(error) |
| 60 | + } |
| 61 | + } catch (error) { |
| 62 | + toast.error(error) |
| 63 | + } finally { |
| 64 | + setIsDownloading(false) |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return { handleDownload, isDownloading } |
| 69 | +} |
| 70 | + |
| 71 | +export default useDownload |
0 commit comments