0

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!

2
  • does the console.log(csvData) give you the expected result? Commented Aug 29, 2019 at 19:10
  • Yes, it's logging the data. Commented Aug 29, 2019 at 19:13

1 Answer 1

3

I've added the following to my getReports function and removed the csvLink component and I was able to export the data to CSV file, but it's definitely not a nice UX. I still need to work on separating the inputs into columns.

const blob = new Blob([csvData], { type: 'text/csv' })
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.setAttribute('hidden', '')
a.setAttribute('href', url)
a.setAttribute('download', 'download.csv')
document.body.appendChild(a)
a.click()
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your answer...if i want to download some of the columns and rows in the table ....how to do it...please let me know...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.