adplus-dvertising

react-csv add dataset dynamically to data list not work

Asked 2 days ago
Viewed 7 times

I'm using the react-csv library and I have an issue.

if I dynamically allocate a dataset and download it through CSVLink, then an empty csv file is downloaded.
but if I use static dataset, it just fine

How do I solve it?

Here is my code

import './App.css';
import { CSVLink } from "react-csv";
import { useState } from 'react';

function App() {

  const [data, setData] = useState([])


  const headers = [
    { label: "gu",  key: "region_2depth_name" },
    { label: "legal_dong", key: "region_3depth_name" },
    { label: "address", key: "address_name" },
    { label: "usage", key: "usage"},
    { label: "lat", key: "lat" },
    { label: "lng", key: "lng" }
  ];

  const addData = () => {
    data.push({
      region_2depth_name: "gu",
      region_3depth_name: "legal_dong",
      address_name: "address",
      usage: "usage",
      lat: "lat",
      lng: "lng"
    })

  }

  return (

    <div>
     
      onClick={addData}>
        Add dataset
      </button>
      <CSVLink data={data} headers={headers}>
        Download me
      </CSVLink>;

    </div>
  );
}

export default App;

asked 2 days ago

Correct Answer

You have to use useState hook setData properly to add properly on the data array.

You can check here for the sample code: https://stackblitz.com/edit/react-84emed?file=src/App.js

answered 2 days ago