0

this is my first question on stackoverflow, i search and tried lot of solutions but i finally decided to ask for help here.

I have seen a similar question without answer here: Cannot fetch .csv data in React

I use reactJs to create a little application and as a database, i want to use a csv file.

i would like to use the fetch method to parse my data (my csv file),

whatever i do, the console.log(data) who should return me the contents of my csv, rather return anything to me instead....

my code :

async function getData() {
const response = await fetch('./private/BookList.csv', {
headers : { 
  'content-type': 'text/csv;charset=UTF-8'
 }
})
.catch(function() {
  console.log("error");
 }); 


const data = await response.text();
console.log(data);
}

in my développer tools , the console.log display this:

console.log

which returns me absolutely anything!

my CSV file contain the following lines :

TITRE,EDITEUR,DIMENSIONS ~ (cm),TYPE,COLLECTION,ETAT,PRIX (€),stock HOUSE OF M,PANNINI COMICS,17*26,RELIÉ,MARVEL,COMME NEUF,20,true

gindev77
  • 1
  • 3
  • Welcome to stack overflow, What do you expect from `console.log(data); `? – Nur Apr 05 '21 at 17:10
  • Hi! thank you for replying me. i expect rows from my csv file. not this html page it return actually. – gindev77 Apr 06 '21 at 06:10
  • my csv file got lines like this : – gindev77 Apr 06 '21 at 06:11
  • i just tried to add The Accept parameter in the headers section, but it is not better : headers : { 'content-type': 'text/csv;charset=UTF-8', 'Accept': 'text/csv;charset=UTF-8' } – gindev77 Apr 06 '21 at 06:31

1 Answers1

0

i found the issue : it was because in react the CSV file must be imported (the weird thing was i do that at the begining but i changed it maybe because my code would'nt work for another reason at this time.

the following code return me an array of titles from my CSV file!

import React, { Component } from 'react';
import { render } from '@testing-library/react';
import './App.css';
import FilterableBooksTable from './Components/FilterableBooksTable';
import DATA from './private/BookList.csv';
const DATA_ARRAY = [];



async function getData() {
const response = await fetch(DATA, {
  headers : { 
    'content-type': 'text/csv;charset=UTF-8'
   }
  })
  .catch(function() {
    console.log("error");
}); 


const data = await response.text();
// console.log(data);

const rows = data.split((/\r?\n|\r/)).slice(1);
// console.log(rows[1]);
rows.forEach(elt => {
        const colums = elt.split(';');
        const titre = colums[0];
        // console.log(titre);
        DATA_ARRAY.push(titre);
})

console.log(DATA_ARRAY);
  }



getData();


function App() {

  return (
    <div className="App">
      <header className="App-header">
  
        <div>
          {/* <FilterableBooksTable books={DATATOPARSE}/> */}
        </div>
      
      </header>
    </div>
  );
}
export default App;

result

gindev77
  • 1
  • 3