I built a small react app that takes data and changes it in some way, then downloads it to a csv file. When I download the file the csv is empty. Here is my code:
const [data, setData] = useState([]);
const downloadBtn = useRef();
useEffect(() => {
if (data.length) {
downloadBtn.current.link.click();
}
}, [data])
const compressData = () => {
const compressedData = [];
// do something with data
setData(compressedData);
}
return(
<button className="btn btn-light btn-outline-secondary" onClick={compressData}>Compress Transactions</button>
<CSVLink
ref={downloadBtn}
className="btn btn-light btn-outline-secondary d-none" // button is hidden
filename="transactions.csv"
data={data}>Compress Transactions</CSVLink>
)
but if I put the click inside a setTimeout like this it works:
setTimeout(() => {
downloadBtn.current.link.click();
}, 1);
I'd really like to know why it happens, and maybe hear about a better way to deal with it.