Created
April 12, 2022 15:41
-
-
Save joeypy/a16c07a96e4e14e15f5b882b512f21b0 to your computer and use it in GitHub Desktop.
Download data into a file
This file contains 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
const downloadFile = ({ data, fileName, fileType }) => { | |
const blob = new Blob([data], { type: fileType }) | |
const a = document.createElement('a') | |
a.download = fileName | |
a.href = window.URL.createObjectURL(blob) | |
const clickEvt = new MouseEvent('click', { | |
view: window, | |
bubbles: true, | |
cancelable: true, | |
}) | |
a.dispatchEvent(clickEvt) | |
a.remove() | |
} | |
const exportToJson = e => { | |
e.preventDefault() | |
downloadFile({ | |
data: JSON.stringify(usersData.users), | |
fileName: 'users.json', | |
fileType: 'text/json', | |
}) | |
} | |
const exportToCsv = e => { | |
e.preventDefault() | |
// Headers for each column | |
let headers = ['Id,Name,Surname,Age'] | |
// Convert users data to a csv | |
let usersCsv = usersData.users.reduce((acc, user) => { | |
const { id, name, surname, age } = user | |
acc.push([id, name, surname, age].join(',')) | |
return acc | |
}, []) | |
downloadFile({ | |
data: [...headers, ...usersCsv].join('\n'), | |
fileName: 'users.csv', | |
fileType: 'text/csv', | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment