Clue Mediator

Loading data asynchronously and download CSV using react-csv

๐Ÿ“…February 3, 2021
๐Ÿ—ReactJS

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

Output - Export data to CSV in React - Clue Mediator

Output - Export data to CSV in React - Clue Mediator

https://www.youtube.com/watch?v=o4JOysBWeos

Steps to download CSV file asynchronously

  1. Create a react app and install package
  2. Handle an API call
  3. Download CSV file
  4. Output

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.

Export data to CSV in React

2. Handle an API call

Here, we will use the JSONPlaceholder fake API to get the list of the user using the GET API.

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.

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}>
      </csvlink></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..!! ๐Ÿ™‚

Demo & Source Code

Github Repository StackBlitz Project