Winsome
Winsome

Reputation: 89

How to import a CSV file in ReactJs?

I am trying to import a csv file that is in a folder called data on the same level as this function. I've tried to incorporate the solution I found on here, but no luck and I don't know what I need to modify.

enter image description here

getData.jsx

import React, { useState, useEffect } from 'react';
import Papa from 'papaparse';

export default function GetData(artist) {
    const data = Papa.parse(fetchCsv);
    console.log(data);
    return data;
}

async function fetchCsv() {
     const response = await fetch('data/artist_data.csv');
     const reader = response.body.getReader();
     const result = await reader.read();
     const decoder = new TextDecoder('utf-8');
     const csv = decoder.decode(result.value);
     return csv;
 }

Upvotes: 3

Views: 13349

Answers (1)

gdh
gdh

Reputation: 13682

Few problems I see here.

  1. When you do fetch('data/mycsv.csv') you are essentially making a request to http://localhost:3000/data/mycsv.csv. Check the n/w tab and you will see the response returned is your html. React first loads your root page and then checks further for routes.
  2. Some coding errors like - you haven't called the fetchCsv fun inside GetData function. Also you need to await for fetchCsv.

Solution:

Move your data folder which has your csv file to the public folder and make corrections to your code.

import React from 'react';
import Papa from 'papaparse';

async function GetData(artist) {
    const data = Papa.parse(await fetchCsv());
    console.log(data);
    return data;
}

async function fetchCsv() {
    const response = await fetch('data/mycsv.csv');
    const reader = response.body.getReader();
    const result = await reader.read();
    const decoder = new TextDecoder('utf-8');
    const csv = await decoder.decode(result.value);
    console.log('csv', csv);
    return csv;
}

I have tested the above code in my local and it works fine.

Upvotes: 9

Related Questions