Created
April 12, 2022 17:14
-
-
Save coreylight/345293db424dd8c1de83854b300ab29b to your computer and use it in GitHub Desktop.
JS client download data on the fly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const downloadData = async ( | |
fileName: string, | |
data: object | string | |
): Promise<void> => { | |
const stringData = typeof data === 'string' ? data : JSON.stringify(data); | |
try { | |
const dataBlob = new Blob([stringData], { type: 'text/json' }); | |
const url = URL.createObjectURL(dataBlob); | |
const link = document.createElement('a'); | |
link.href = url; | |
link.setAttribute('download', fileName); | |
document.body.appendChild(link); | |
link.click(); | |
link.parentNode?.removeChild(link); | |
} catch (err) { | |
console.error(err); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment