I'm trying to pass data from external api and convert it to a CSV file. This is what I have so far:
import React, { Component } from 'react';
import { CSVLink } from "react-csv";
import Header from './components/header'
import './App.scss'
class App extends Component {
constructor() {
super()
this.state = {
orders: []
}
this.getReports = this.getReports.bind(this)
}
getReports = async () => {
const response = await fetch('example.com')
const ordersData = await response.json()
this.setState({
orders: ordersData.data,
})
let order = this.state.orders.map(order => ({
ID: order.id,
Order_ID: order.order_id,
Date: order.created,
Amount: order.total_amount,
Payment_Provider: order.payments[0].provider_id,
Payment_ID: order.payments[0].id,
Refund_Reason: order.reason
}))
const objectToCsv = (order) => {
const csvRows = [];
const headers = Object.keys(order[0])
csvRows.push(headers.join(','));
// console.log(csvRows)
for (const row of order) {
const values = headers.map(header => {
const escaped = ('' + row[header]).replace(/"/g, '\\"')
return `"${escaped}"`
})
csvRows.push(values.join(','))
}
return csvRows.join('\n')
}
let csvData = objectToCsv(order)
console.log(csvData)
// console.log(order)
// console.log(this.state.orders)
}
render() {
return (
<div className="App">
<Header />
<div className="body">
{/* <button onClick={this.getReports}>CLICK</button> */}
<CSVLink data={csvData} onClick={this.getReports}>Click me</CSVLink>
</div>
</div>
);
}
}
export default App;
The problem I'm facing is that I can't pass the csvData variable to the data attribute in the CsvLink component since the variable is not global. I tried adding another csvData state where I passed the objectToCsv(order) and that stops the error, however when I download the CSV, the content is jiberish. Any help is much appreciated!
console.log(csvData)give you the expected result?