'Loading data asynchronously and downloading CSV data with a click is one step behind the latest retrieved data

using the react-csv package, I am loading data asynchronously and then trying to download the retrieved data from the server with one click. The problem I am currently facing is that the click is a step behind the current state. When the component first renders it downloads an empty CSV file and on the second click it downloads the data from the previous fetch, not the current/latest fetch.That is the same situation that is described here , but the solution mentioned there didn't work in my case : se here is the code am working on :

  const [newData, setNewData] = useState([]);
  const csvLink = React.createRef();

   const csvExport = (
    <div>
      <Button className="pull-right title-button" onClick={getData}>
        CSV Export
      </Button>
      <CSVLink data={newData} headers={headers} target="_blank" ref={csvLink}></CSVLink>
    </div>
  );

const getData = async () => {
    await getRetailLinkOutcomes(auth, startDate, endDate, 0, 0, filters, sort, sortDirection, false).then((response) => {
      setNewData(response.records);
      csvLink.current.link.click();
    });
  };


Solution 1:[1]

Elaborating more on what N.A mentioned in the comments:

  const [data, setData] = useState([])
  const [headers, setHeaders] = useState([])
  const excelRef = useRef()

The function to fecth data :

    function requestAllHistory () {
        console.log('requesting excel history')
        requestAllHistoryForExcel(function (response, error) {
        // data and headers fetched
        setData(data)
        setHeaders(headers)
    })
}

Inside useEffect

  useEffect(() => {
    if (headers.length > 0) {
      console.log('ExportExcel useEffect', headers)
      excelRef.current.link.click()
    }
  }, [headers])

The CSVLink should not be displayed on the UI (display:'none')

   return (
    <span>
      <button
        type='button'
        className='btn btn-lg btn-dark'
        onClick={() => requestAllHistory()}
      >
        <span> Export to Excel </span>
        <span className='download'></span>
      </button>
      <CSVLink
        data={data}
        headers={headers}
        filename={filename}
        ref={excelRef}
        className='hiddenExcel'
        target='_blank'
      ></CSVLink>
    </span>
  )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mnagdev