Reputation: 47
so I'm generating an invoice, and am using the react-csv package to covert my graphql data into a csv file. problem is I don't want the user to select a location locally to download to (out of the box behavior). It needs to be saved automatically in a hardcoded directory in the server. Anyone???
<CSVLink onClick={generateInvoice} className="mt-1 inline-block align-middle w-full inline-flex justify-center py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-400 hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" filename={csvfilename} data={csvinvoiceForDownload} headers={headers}>
Create Invoice
</CSVLink>
Upvotes: 1
Views: 794
Reputation: 167
You dont need react-csv, it is for rendering data...
You can use eg PapaParse
https://www.papaparse.com/docs#json-to-csv
to convert your graphQL object into csv, which you can send with fetch or axios to your server...
// With implicit header row
// (keys of first object populate header row)
var csv = Papa.unparse([
{
"Column 1": "foo",
"Column 2": "bar"
},
{
"Column 1": "abc",
"Column 2": "def"
}
]);
Also you can just use js:
const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
header.join(','), // header row first
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
console.log(csv)
(example found on SO: How to convert JSON to CSV format and store in a variable)
you can find there more options...
Upvotes: 1