1

I'm building a web app with nextjs & typescript. I have a chart which I want to display and would like to use a csv file for the data (let me know if using csv is a bad choice - I guess in the end I will probably add this data to my backend server so I can have it up to date and serve it from an api).

I saved the csv file mydata.csv in /public. Should I be using a library such as papaparse - if so how can I pass the file to the parser? There is also this solution which I found here How do I import a file with a space using next.js? but when I try:const dt = import('../../public/mydata.csv') I get the error "Cannot find module '../../public/mydata.csv' or its corresponding type declarations.ts(2307)"

sev
  • 1,500
  • 17
  • 45

1 Answers1

0

The format import dt from '../../public/mydata.csv'; works just well for me when it's implemented along with the webpack solution you've linked to.

The issue could be that the IDE you're using doesn't understand next.config.js (mine doesn't and shows this error).

The app, however, builds and runs just fine, giving me parsed csv contents (without the need to use papaparse.

Igor Loskutov
  • 2,157
  • 2
  • 20
  • 33
  • Is this solution in anyway preferable over the papaparse method? – sev May 18 '22 at 18:59
  • It reads a bit cleaner. I'd personally use this one if I needed to preload a static csv, resorting to papaparse only on huge data when I want to explore what performance optimization it would give. Papaparse would involve reading a local file, as I understand, which is more code. – Igor Loskutov May 18 '22 at 19:02
  • You're right, this works - but vscode still complains and the typescript type is just promise so it does not know the names of the columns... Can I somehow fix that? – sev May 19 '22 at 13:46
  • that's strange, my ts is just fine about it; it's a proper CSV for it... it was a promise only when I did `const dt = import('../../public/mydata.csv')` – Igor Loskutov May 19 '22 at 16:49
  • I can't really believe how difficult it is to just use a csv in nextjs/react/typescript/javascript Is it just that this is not a done thing at all? I actually asked a related question here https://stackoverflow.com/questions/72308172/how-to-store-numeric-data-for-nextjs-react-website-csv-file-backend-api-call – sev May 19 '22 at 16:53
  • It's not a usual case to just "import" it. Import is a kind of "sugar" for reading it from the file system. I'd try something like this person did https://stackoverflow.com/a/60342410/2123547 - with papaparse : ), In your getStaticProps / getServerSideProps – Igor Loskutov May 19 '22 at 17:01