This might be a really simple thing to do and there are multiple Q&A regarding this, but i can't find a solution to my problem..
I'm trying to parse an entire CSV file with d3-request module and set the state with this data in a React component. From my understanding the d3-request module parses each row of the CSV file one by one, so I can't simply do this:
import {csv} from 'd3-request';
componentWillMount() {
csv('./data/test.csv', (error, data) => {
if (error) {
this.setState({loadError: true});
}
this.setState({
data: data
});
})
}
So i thought of doing this instead. The "..." or spread syntax helps to copy each array.
componentWillMount() {
csv('./data/elements-by-episode.csv', (error, data) => {
if (error) {
this.setState({loadError: true});
}
this.setState({
data: data.map(d => ({...d}))
});
})
}
render() {
console.log(this.state.data);
}
But the console.log prints out the html contents of the page itself.
test.csv
'title', 'A', 'B'
'E01', 1, 0
'E02', 5, 0
'E03', 10, 2
Hoping to transform CSV to this, after parsing:
this.state.date = [
['title', 'A', 'B'],
['E01', 1, 0],
['E02', 5, 0],
['E03', 10, 2]
];
EDIT:
Seems that the problem in the first place is reading in the CSV file using d3-request in React app.
componentWillMount() {
csv('test.csv', (error, data) =>
console.log(data);
});
}
Console log prints out the HTML structure of the page....
I was facing the same error some time ago and a way to solve it is as follows.
import React, { Component } from 'react';
import * as d3 from 'd3';
import data from './data.csv';
d3.csv(data, function(data) { console.log(data); });
You need to import your dataset first using React's method "Import" and then parse it using D3.csv function.
Hope it works for you! All the best.
Edit: I am using D3.js 5.5.0 and React.js 16.4.1 and using Yarn to start the application.
import React, {Component} from 'react';
import './App.css';
import * as d3 from 'd3';
import data from './data_set/data.csv';
class App extends Component {
constructor(props) {
super(props)
}
componentDidMount() {
d3.csv(data).then(function(data) {
console.log(data)
}).catch(function(err) {
throw err;
})
}
render() {
return (
<div className = "App" >
<div> Data Visualization </div>
</div>
);
}
}
export default App;
Making use of promises will do the job ;).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With