2

I have a question re: how to load data from CSV into an array in React -- specifically inside the this.state as an object.

Lets say I start with this, where the state is just hardcoded values.

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      cards: [
        {itemname: 'Item 1',
          restoname: 'Resto 1',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1515191165/bkf4niv9okipbc8y6o8h.jpg',
          description: 'Desc 1'},
        {itemname: 'Item 2',
          restoname: 'Resto 2',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1514060352/twhriy3hvbzayktrjp91.jpg',
          description: 'Desc 2'}
      ]
    };
  }

Is there a way for me to read in that data instead from a CSV where the data is like this?

enter image description here

Thanks everyone!

2 Answers 2

1

Try this npm package. This will help you convert csv to json which you can easily use in your react component - https://www.npmjs.com/package/csvtojson

import csv from 'csvtojson';
const csvFilePath='<path to csv file>';
csv()
.fromFile(csvFilePath)
.on('json',(jsonObj)=>{
    // combine csv header row and csv line to a json object
    // jsonObj.a ==> 1 or 4
})
.on('done',(error)=>{
    console.log('end')
})
Sign up to request clarification or add additional context in comments.

3 Comments

Hey I am getting error can't find variable csv. Can you please help to resolve it?
you need to import it
yes i did that, but after that i am getting another eror \node_modules\\csvtojson\\v2\\Converter.js","targetModuleName":"stream","message":"Unable to resolve modulestream
0

I don't think you can use the csvtojson on the React Native environment.
It works in node but didn't work on Expo, and I think for the RN is the same.

If you just need data from local, then convert CSV into JSON and import it. No extra library needed.
I think this is the easiest.

https://stackoverflow.com/a/59746430/1593212

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.