React: import csv file and parse
Here's a similar example using React Hooks -
import React from 'react'
import Papa from 'papaparse'
export default function() {
const [rows, setRows] = React.useState([])
React.useEffect(() => {
async function getData() {
const response = await fetch('/data/nodes.csv')
const reader = response.body.getReader()
const result = await reader.read() // raw array
const decoder = new TextDecoder('utf-8')
const csv = decoder.decode(result.value) // the csv text
const results = Papa.parse(csv, { header: true }) // object with { data, errors, meta }
const rows = results.data // array of objects
setRows(rows)
}
getData()
}, []) // [] means just do this once, after initial render
return (
<div className="app">
<Table cols={tripColumns} rows={rows} />
</div>
)
}
To answer my own question, I was able to rewrite it like this (/src/controllers/data-controller/data-controller.js
, added the full code for better clarity):
import React from 'react';
import Papa from 'papaparse';
import {withRouter} from 'react-router-dom';
class DataController extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.getData = this.getData.bind(this);
}
componentWillMount() {
this.getCsvData();
}
fetchCsv() {
return fetch('/data/data.csv').then(function (response) {
let reader = response.body.getReader();
let decoder = new TextDecoder('utf-8');
return reader.read().then(function (result) {
return decoder.decode(result.value);
});
});
}
getData(result) {
this.setState({data: result.data});
}
async getCsvData() {
let csvData = await this.fetchCsv();
Papa.parse(csvData, {
complete: this.getData
});
}
render() {
return (
<section className="data-controller">
...
</section>
);
}
}
export default withRouter(DataController);
Here I use the built in fetch to get it like a stream and then read the stream using the build in stream reader, and decode the data using TextDecoder
. I had to move the file also. Before it was located in /src/controllers/data-controller
but I had to move it to /public/data
.