I have Node.Js backend and react front-end. I have a query in the backend that returning data based on category name that I enter in an input box. Before I add onClick event in the button it returned the results in a CSV and download it for me. After adding onClick to the button I can see that at the backend I have a successful query but at the front-end, it's not downloading my results in a csv file. I'm using the button from Semantic UI React and CSVLINK from 'react-csv' package.
Here is my code(function that I called in onClick):
handleReportButton(e){
e.preventDefault();
const value = e.target.value;
fetch(`/reportOnAnswersCategory`,{
method: 'POST',
body: JSON.stringify({
answer: value
}),
headers: {"Content-Type": "application/json"}
})
.then(data => data.json())
.then((data) => {this.setState({report : data});})
.catch(err => console.error(err));
}
This is the button(I have binded the function before, and I did 'const { report } = this.state;' before return):
<Button onClick={this.handleReportButton}>
<CSVLink data={report} >Download this report</CSVLink>
</Button>
Thanks in advance for the help
handleReportis asynchronous, so the report data isn't ready until the fetch results come back. Whereas theCSVLinkexpects the data there already. You can useCSVDownloadto let the link do the downloading too.CSVDownload?<CSVDownload data={report} target="_blank" />, this way it's triggering after call component 2: I have added this line after '.catc(...' in handleReport =>return (<CSVDownload data={this.state.report} target="_blank" />);this way nothing happend