Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract data to React state from CSV file using Papa Parse?

I'm using Papa Parse to parse a CSV file for Graphs. I want to store the data in React state after the file is parsed. Papa.Parse() doesn't return anything and results are provided asynchronously to a callback function. Also, setState() doesn't work inside a async callback. This question is similar to Retrieving parsed data from CSV.

I tried storing the data in state using below code, but as expected it didn't work.

componentWillMount() {

    function getData(result) {
      console.log(result); //displays whole data
      this.setState({data: result}); //but gets error here
    }

    function parseData(callBack) {
      var csvFilePath = require("./datasets/Data.csv");
      var Papa = require("papaparse/papaparse.min.js");
      Papa.parse(csvFilePath, {
        header: true,
        download: true,
        skipEmptyLines: true,
        complete: function(results) {
          callBack(results.data);
        }
      });
    }

    parseData(getData);
}

Here's the error I get when I set state inside getData(). enter image description here

The data is usable inside getData(), but I want to extract it.

How should I store the data in state or in some other variable so that I can use it for Graphs?

like image 272
Amanshu Kataria Avatar asked Oct 20 '17 13:10

Amanshu Kataria


People also ask

How do I extract data from a CSV file in react?

The handleParse function will parse the CSV data using the papa parser and set the data state to the columns of the CSV file. Then we finally return the component which contains an input element to take the uploaded file, a button to parse the data on click, and a container to show any errors or parsed data.

How do you use Papa parse?

To get started with Papa Parse, first import the library. import Papa from 'papaparse'; When using the parse function, you can either choose to parse a string of delimited text, a local file, or a remote file URL. For this example, we will be parsing a local file that we received from React Dropzone in part one.

Can you parse CSV?

Programs store CSV files as simple text characters; a comma separates each data element, such as a name, phone number or dollar amount, from its neighbors. Because of CSV's simple format, you can parse these files with practically any programming language.

What does it mean to parse a csv file?

Parsing a file means reading the data from a file. The file may contain textual data so-called text files, or they may be a spreadsheet.


2 Answers

The problem:

You try to call this.setState in the function getData. But this does not exist in the context of this function.

The solution:

I would try to not write function in functions, but write the functions in the class.

You class could look like this:

import React, { Component } from 'react';

class DataParser extends Component {

  constructor(props) {
    // Call super class
    super(props);

    // Bind this to function updateData (This eliminates the error)
    this.updateData = this.updateData.bind(this);
  }

  componentWillMount() {

    // Your parse code, but not seperated in a function
    var csvFilePath = require("./datasets/Data.csv");
    var Papa = require("papaparse/papaparse.min.js");
    Papa.parse(csvFilePath, {
      header: true,
      download: true,
      skipEmptyLines: true,
      // Here this is also available. So we can call our custom class method
      complete: this.updateData
    });
  }

  updateData(result) {
    const data = result.data;
    // Here this is available and we can call this.setState (since it's binded in the constructor)
    this.setState({data: data}); // or shorter ES syntax: this.setState({ data });
  }

  render() {
    // Your render function
    return <div>Data</div>
  }
}

export default DataParser;
like image 186
Larce Avatar answered Nov 14 '22 21:11

Larce


You need to bind the getData():

function getData(result) {
    console.log(result); // displays whole data
    this.setState({data: result}); // but gets error here
}.bind(this)
like image 32
Sandip Kumar Sharma Avatar answered Nov 14 '22 22:11

Sandip Kumar Sharma