2

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;
 }
Winsome
  • 79
  • 1
  • 5
  • 12
  • https://stackoverflow.com/questions/44769051/how-to-upload-and-read-csv-files-in-react-js – costal oktopus Apr 25 '20 at 01:03
  • You will need import the csv to your project using some tool like some of this: https://stackoverflow.com/questions/52210467/adding-a-csv-file-to-a-webpack-build then you can `import csv from 'data/artist_data.csv'` – Kevyn Klava Apr 25 '20 at 02:27
  • You can also use csv-parse https://stackoverflow.com/a/72404267/343900 – keemor May 27 '22 at 10:54

1 Answers1

7

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.

gdh
  • 13,114
  • 2
  • 16
  • 28