Loading data asynchronously and download CSV using react-csv
Today, we will show you how to load data asynchronously and download CSV using react-csv.
In the previous article, we have explained about the export static data to CSV in React. Here, we will call an API to get the user list and export the CSV file using the react-csv npm package.
Demo Application
Steps to download CSV file asynchronously
1. Create a react app and install package
Let’s create a react application using the create-react-app
and install the react-csv
npm package. Refer to the following link for step by step implementation.
2. Handle an API call
Here, we will use the JSONPlaceholder fake API to get the list of the user using the GET API.
1 2 3 4 | getUserList = () => { return fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()); } |
3. Download CSV file
Based on the API result, we will generate a CSV and handle the export functionality using the react-csv
package. In the following code, we have used the refs
to handle the click event of the CSVLink.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import React, { Component } from 'react'; import { CSVLink } from "react-csv"; const headers = [ { label: "Name", key: "name" }, { label: "Username", key: "username" }, { label: "Email", key: "email" }, { label: "Phone", key: "phone" }, { label: "Website", key: "website" } ]; class AsyncCSV extends Component { constructor(props) { super(props); this.state = { data: [] } this.csvLinkEl = React.createRef(); } getUserList = () => { return fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()); } downloadReport = async () => { const data = await this.getUserList(); this.setState({ data: data }, () => { setTimeout(() => { this.csvLinkEl.current.link.click(); }); }); } render() { const { data } = this.state; return ( <div> <input type="button" value="Export to CSV (Async)" onClick={this.downloadReport} /> <CSVLink headers={headers} filename="Clue_Mediator_Report_Async.csv" data={data} ref={this.csvLinkEl} /> </div> ); } } export default AsyncCSV; |
4. Output
Run the application and check the output in the browser.
I hope you find this article is helpful.
Thank you for reading. Happy Coding..!! 🙂