Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  119] [ 5]  / answers: 1 / hits: 22491  / 7 Years ago, fri, october 20, 2017, 12:00:00

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



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?


More From » json

 Answers
7

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;

[#56173] Tuesday, October 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;