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

I use Para Parse to analyze the CSV file for graphs. I want to save the data in React state after the file is parsed. Papa.Parse () returns nothing, and the results are provided asynchronously to the callback function. In addition, setState () does not work inside an asynchronous callback. This question is similar to Getting Analyzed Data from CSV .

I tried to keep the data in a state using the code below, but as expected, it did not 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);
}

This is where the error occurs when I set the state inside getData (). enter image description here

Data can be used inside getData (), but I want to extract it.

- , Graphs?

+4
1

:

this.setState getData. .

:

, .

:

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 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;
+4

Source: https://habr.com/ru/post/1687876/


All Articles