add dataset dynamically to data list not work

Viewed 17

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;
1 Answers

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

const addData = () => {
  setData((oldData) => [
    ...oldData,
    {
      region_2depth_name: 'gu',
      region_3depth_name: 'legal_dong',
      address_name: 'address',
      usage: 'usage',
      lat: 'lat',
      lng: 'lng',
    },
  ]);
};

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

Related