import React, { Component } from 'react' import csv from 'parse-csv' import C3Chart from 'react-c3js' import 'c3/c3.css' import './chart.css' import { rainbow, bigRainbow, colorTable } from './constants' class SinglePieChart extends Component { state = { keys: [], data: [], } componentDidMount() { const { payload } = this.props fetch(payload.url, { mode: 'cors' }) .then(r => r.text()) .then(text => { try { const keys = text.split('\n')[0].split(',').map(s => s.trim().replace(/"/, '')) const data = csv.toJSON(text, { headers: { included: true } }) this.setState({ keys, data }) } catch (e) { console.error("error making json:", payload.url) console.error(e) } }) } render() { const { fields } = this.props.payload const { keys, data } = this.state // console.log(keys, data) const [labelField, numberField] = keys if (!data.length) return null const rowsToDisplay = parseInt(fields.Top, 10) const rows = data.map(row => { const label = row[labelField] const number = parseFloat(row[numberField]) return [label, number] }).sort((a, b) => b[1] - a[1]) let chartRows = rows.slice(0, rowsToDisplay) let otherCount = rows.slice(rowsToDisplay).reduce((a, b) => a + b[1], 0) if (otherCount > 0) { chartRows.push([fields.OtherLabel, otherCount]) } const height = chartRows.length < 6 ? 316 : chartRows.length < 10 ? 336 : 356 const pattern = colorTable[fields.Colors] || (chartRows.length < 10 ? rainbow : bigRainbow) return (