Skip to content
This repository has been archived by the owner on Jan 9, 2023. It is now read-only.

Commit

Permalink
feat(incidentscsv): made functions more abstract
Browse files Browse the repository at this point in the history
made getcsv and downloadlink functions

re #2292
  • Loading branch information
reidmeyer committed Aug 23, 2020
1 parent a5f60b2 commit 1fb36c9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
19 changes: 3 additions & 16 deletions src/incidents/list/ViewIncidentsTable.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Spinner, Table, Dropdown } from '@hospitalrun/components'
import format from 'date-fns/format'
import { Parser } from 'json2csv'
import React from 'react'
import { useHistory } from 'react-router'

import useTranslator from '../../shared/hooks/useTranslator'
import { DownloadLink, getCSV } from '../../shared/util/DataHelpers'
import { extractUsername } from '../../shared/util/extractUsername'
import useIncidents from '../hooks/useIncidents'
import IncidentSearchRequest from '../model/IncidentSearchRequest'
Expand Down Expand Up @@ -50,10 +50,7 @@ function ViewIncidentsTable(props: Props) {
function downloadCSV() {
populateExportData()

const fields = Object.keys(exportData[0])
const opts = { fields }
const parser = new Parser(opts)
const csv = parser.parse(exportData)
const csv = getCSV(exportData)

const incidentsText = t('incidents.label')

Expand All @@ -62,17 +59,7 @@ function ViewIncidentsTable(props: Props) {
.concat(format(new Date(Date.now()), 'yyyy-MM-dd--hh-mma'))
.concat('.csv')

const text = csv
const element = document.createElement('a')
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`)
element.setAttribute('download', filename)

element.style.display = 'none'
document.body.appendChild(element)

element.click()

document.body.removeChild(element)
DownloadLink(csv, filename)
}

const dropdownItems = [
Expand Down
22 changes: 22 additions & 0 deletions src/shared/util/DataHelpers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Parser } from 'json2csv'

export function getCSV<T>(data: T[]): string {
const fields = Object.keys(data[0])
const opts = { fields }
const parser = new Parser(opts)
const csv = parser.parse(data)
return csv
}

export function DownloadLink(data: string, fileName: string) {
const text = data
const element = document.createElement('a')
element.setAttribute('href', `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`)
element.setAttribute('download', fileName)

element.style.display = 'none'
document.body.appendChild(element)
element.click()

return document.body.removeChild(element)
}

0 comments on commit 1fb36c9

Please sign in to comment.