How to export CSV and JSON data from API in React

How to export CSV and JSON data from API in React

In this blog, we will explore how to fetch data from an API using Axios, and then export the data as both CSV and JSON files using the Papa Parse library.

Exporting Data as CSV using Papa Parse

Papa Parse is a powerful JavaScript library that can be used to parse and convert CSV data. In this example, we will use Papa Parse to convert the data fetched from the API to a CSV format, and then export it as a file.

To use Papa Parse, you need to install it in your project. You can do this by running npm install papaparse or yarn add papaparse in your project directory.

Once you have installed Papa Parse, you can use the Papa.parse() method to parse CSV data, and the Papa.unparse() method to convert JSON data to CSV format. Here's an example code snippet that demonstrates how to do this:

import axios from 'axios';
import Papa from 'papaparse';

// Function to export data as a file
  const exportData = (data, fileName, type) => {
    // Create a link and download the file
    const blob = new Blob([data], { type });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };

// Fetch data from API endpoint
axios.get('/api/data')
  .then(response => {
    // Convert data to CSV format
    const csvData = Papa.unparse(response.data);
    exportData(csvData, 'data.csv', 'text/csv;charset=utf-8;');
  })
  .catch(error => {
    // Handle errors
    console.error(error);
  });

In this example, the axios.get() method is used to fetch data from the /api/data endpoint. The then() method is then used to convert the data to CSV format using the Papa.unparse() method.

The resulting CSV data is then downloaded as a file using a link element that is created dynamically in the DOM. This allows the user to download the CSV data as a file named data.csv.

Exporting Data as JSON

Exporting data as JSON doesn't require the Papa Parse library. You can simply use the JSON.stringify() method to convert a JavaScript object to a JSON string, and then download the string as a file.

import axios from 'axios';

// Function to export data as a file
  const exportData = (data, fileName, type) => {
    // Create a link and download the file
    const blob = new Blob([data], { type });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
  };

// Fetch data from API endpoint
axios.get('/api/data')
  .then(response => {
    // Convert data to JSON format
    const jsonData = JSON.stringify(response.data);
    exportData(jsonData, "data.json", 'application/json');
  })
  .catch(error => {
    // Handle errors
    console.error(error);
  });