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().
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?