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 = () => {
      region_2depth_name: "gu",
      region_3depth_name: "legal_dong",
      address_name: "address",
      usage: "usage",
      lat: "lat",
      lng: "lng"


  return (

        Add dataset
      <CSVLink data={data} headers={headers}>
        Download me


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:

answered 2 days ago