Skip to content

Commit 24dd32b

Browse files
committed
feat: add hook use download
1 parent 472282b commit 24dd32b

File tree

4 files changed

+76
-0
lines changed

4 files changed

+76
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { default as useDownload } from './UseDownload'
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { Host } from '@Common/Constants'
2+
3+
export const getDownloadResponse = (downloadUrl: string) => fetch(`${Host}/${downloadUrl}`)

src/Shared/Hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@
1515
*/
1616

1717
export * from './UsePrompt'
18+
export * from './UseDownload'

0 commit comments

Comments
 (0)