Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS + D3: Parse local CSV file and passing it to state with d3-request

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....

like image 754
doyz Avatar asked Jul 10 '18 06:07

doyz


2 Answers

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.

like image 107
Jorge Quintana Avatar answered Nov 18 '22 02:11

Jorge Quintana


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 ;).

like image 26
Divyanshu Rawat Avatar answered Nov 18 '22 03:11

Divyanshu Rawat