calling dynamic response with d3 bar graph in react application

Viewed 88

i was trying render the dynamic response and using d3 charts actually this application is developed using recharts so started implementing using d3 so here i included d3 the bard3 has an issue not rendering the data properly and throwing this error.

error

TypeError: Cannot read property 'count' of undefined
BarChartD3
src/components/BarChart.js:64

      ×
TypeError: Cannot read property 'count' of undefined
(anonymous function)
src/components/BarChart.js:12
   9 | const width = 500;
  10 | const margin = { top: 20, right: 30, bottom: 30, left: 40 };
  11 | 
> 12 | const x = d3
     | ^  13 |     .scaleBand()
  14 |     .domain(data.map((d) => d.Orders.count))
  15 |     .rangeRound([margin.left, width - margin.right])
View compiled
(anonymous function)
src/components/BarChart.js:12
   9 | const width = 500;
  10 | const margin = { top: 20, right: 30, bottom: 30, left: 40 };
  11 | 
> 12 | const x = d3
     | ^  13 |     .scaleBand()
  14 |     .domain(data.map((d) => d.Orders.count))
  15 |     .rangeRound([margin.left, width - margin.right])
View compiled
(anonymous function)
src/components/useD3.js:8
   5 | const ref = React.useRef();
   6 | 
   7 | React.useEffect(() => {
>  8 |     renderChartFn(d3.select(ref.current));
     | ^   9 |     return () => {};
  10 |   }, dependencies);
  11 | return ref;

resultset data this is the resultant data i was trying to render it but failing at some point

loadResponse:
annotation:
dimensions: {}
measures: {Orders.count: {…}, Products.count: {…}, LineItems.count: {…}, Orders.totalAmount: 
{…}, LineItems.cumulativeTotalRevenue: {…}, …}
segments: {}
timeDimensions: {Orders.completedAt.day: {…}, Orders.completedAt: {…}}
__proto__: Object
data: Array(30)
0: {Orders.completedAt.day: "2021-02-12T00:00:00.000", Orders.completedAt: "2021-02- 
12T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "11", …}
1: {Orders.completedAt.day: "2021-02-13T00:00:00.000", Orders.completedAt: "2021-02- 
13T00:00:00.000", Orders.count: "7", Products.count: "7", LineItems.count: "15", …}
2: {Orders.completedAt.day: "2021-02-14T00:00:00.000", Orders.completedAt: "2021-02- 
14T00:00:00.000", Orders.count: "8", Products.count: "8", LineItems.count: "15", …}
3: {Orders.completedAt.day: "2021-02-15T00:00:00.000", Orders.completedAt: "2021-02- 
15T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "15", …}
4: {Orders.completedAt.day: "2021-02-16T00:00:00.000", Orders.completedAt: "2021-02- 
16T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "11", …}
5: {Orders.completedAt.day: "2021-02-17T00:00:00.000", Orders.completedAt: "2021-02- 
17T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "12", …}
6: {Orders.completedAt.day: "2021-02-18T00:00:00.000", Orders.completedAt: "2021-02- 
18T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "8", …}
7: {Orders.completedAt.day: "2021-02-19T00:00:00.000", Orders.completedAt: "2021-02- 
19T00:00:00.000", Orders.count: "4", Products.count: "4", LineItems.count: "8", …}
8: {Orders.completedAt.day: "2021-02-20T00:00:00.000", Orders.completedAt: "2021-02- 
20T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "15", …}
9: {Orders.completedAt.day: "2021-02-21T00:00:00.000", Orders.completedAt: "2021-02- 
21T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "5", …}
10: {Orders.completedAt.day: "2021-02-22T00:00:00.000", Orders.completedAt: "2021-02- 
22T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "14", …}
11: {Orders.completedAt.day: "2021-02-23T00:00:00.000", Orders.completedAt: "2021-02- 
23T00:00:00.000", Orders.count: "1", Products.count: "1", LineItems.count: "2", …}
12: {Orders.completedAt.day: "2021-02-24T00:00:00.000", Orders.completedAt: "2021-02- 
24T00:00:00.000", Orders.count: "10", Products.count: "10", LineItems.count: "20", …}
13: {Orders.completedAt.day: "2021-02-25T00:00:00.000", Orders.completedAt: "2021-02- 
25T00:00:00.000", Orders.count: "9", Products.count: "9", LineItems.count: "22", …}
14: {Orders.completedAt.day: "2021-02-26T00:00:00.000", Orders.completedAt: "2021-02- 
26T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "14", …}
15: {Orders.completedAt.day: "2021-02-27T00:00:00.000", Orders.completedAt: "2021-02- 
27T00:00:00.000", Orders.count: "3", Products.count: "3", LineItems.count: "6", …}
16: {Orders.completedAt.day: "2021-02-28T00:00:00.000", Orders.completedAt: "2021-02- 
28T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "13", …}
17: {Orders.completedAt.day: "2021-03-01T00:00:00.000", Orders.completedAt: "2021-03- 
01T00:00:00.000", Orders.count: "1", Products.count: "1", LineItems.count: "1", …}
18: {Orders.completedAt.day: "2021-03-02T00:00:00.000", Orders.completedAt: "2021-03- 
02T00:00:00.000", Orders.count: "9", Products.count: "9", LineItems.count: "21", …}
19: {Orders.completedAt.day: "2021-03-03T00:00:00.000", Orders.completedAt: "2021-03- 
03T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "10", …}
20: {Orders.completedAt.day: "2021-03-04T00:00:00.000", Orders.completedAt: "2021-03- 
04T00:00:00.000", Orders.count: "3", Products.count: "3", LineItems.count: "3", …}
21: {Orders.completedAt.day: "2021-03-05T00:00:00.000", Orders.completedAt: "2021-03- 
05T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "10", …}
22: {Orders.completedAt.day: "2021-03-06T00:00:00.000", Orders.completedAt: "2021-03- 
06T00:00:00.000", Orders.count: "5", Products.count: "5", LineItems.count: "14", …}
23: {Orders.completedAt.day: "2021-03-07T00:00:00.000", Orders.completedAt: "2021-03- 
07T00:00:00.000", Orders.count: "4", Products.count: "4", LineItems.count: "7", …}
24: {Orders.completedAt.day: "2021-03-08T00:00:00.000", Orders.completedAt: "2021-03- 
08T00:00:00.000", Orders.count: "4", Products.count: "2", LineItems.count: "5", …}
25: {Orders.completedAt.day: "2021-03-09T00:00:00.000", Orders.completedAt: "2021-03- 
09T00:00:00.000", Orders.count: "8", Products.count: "8", LineItems.count: "17", …}
26: {Orders.completedAt.day: "2021-03-10T00:00:00.000", Orders.completedAt: "2021-03- 
10T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "10", …}
27: {Orders.completedAt.day: "2021-03-11T00:00:00.000", Orders.completedAt: "2021-03- 
11T00:00:00.000", Orders.count: "1", Products.count: "1", LineItems.count: "2", …}
28: {Orders.completedAt.day: "2021-03-12T00:00:00.000", Orders.completedAt: "2021-03- 
12T00:00:00.000", Orders.count: "4", Products.count: "4", LineItems.count: "5", …}
29: {Orders.completedAt.day: "2021-03-13T00:00:00.000", Orders.completedAt: "2021-03- 
13T00:00:00.000", Orders.count: "6", Products.count: "6", LineItems.count: "10", …}
length: 30
__proto__: Array(0)
lastRefreshTime: "2021-03-14T09:28:12.152Z"
query: {measures: Array(7), timeDimensions: Array(1), dimensions: Array(0), segments: 
Array(0), filters: Array(0), …}
slowQuery: false
__proto__: Object
__proto__: Object

barChart.js

import { useD3 } from './useD3';
import React from 'react';
import * as d3 from 'd3';
const productcount = 0
function BarChartD3({ data }) {
    const ref = useD3(
        (svg) => {
            const height = 500;
            const width = 500;
            const margin = { top: 20, right: 30, bottom: 30, left: 40 };

            const x = d3
                .scaleBand()
                .domain(data.map((d) => d.Orders.completedAt))
                .rangeRound([margin.left, width - margin.right])
                .padding(0.1);

            const y1 = d3
                .scaleLinear()
                .domain([0, d3.max(data, (d) => d.Orders.totalAmount || productcount)])
                .rangeRound([height - margin.bottom, margin.top]);

            const xAxis = (g) =>
                g.attr("transform", `translate(0,${height - margin.bottom})`).call(
                    d3
                        .axisBottom(x)
                        .tickValues(
                            d3
                                .ticks(...d3.extent(x.domain()), width / 40)
                                .filter((v) => x(v) !== undefined)
                        )
                        .tickSizeOuter(0)
                );

            const y1Axis = (g) =>
                g
                    .attr("transform", `translate(${margin.left},0)`)
                    .style("color", "steelblue")
                    .call(d3.axisLeft(y1).ticks(null, "s"))
                    .call((g) => g.select(".domain").remove())
                    .call((g) =>
                        g
                            .append("text")
                            .attr("x", -margin.left)
                            .attr("y", 10)
                            .attr("fill", "currentColor")
                            .attr("text-anchor", "start")
                            .text(data.y1)
                    );

            svg.select(".x-axis").call(xAxis);
            svg.select(".y-axis").call(y1Axis);

            svg.select(".plot-area")
                .attr("fill", "steelblue")
                .selectAll(".bar")
                .data(data)
                .join("rect")
                .attr("class", "bar")
                .attr("x", (d) => x(d.Orders.completedAt))
                .attr("width", x.bandwidth())
                .attr("y", (d) => y1(d.Orders.totalAmount || productcount))
                .attr("height", (d) => y1(0) - y1(d.Orders.totalAmount || productcount));
        },
        [data.length]
    );

    return (
        <svg
            ref={ref}
            style={{
                height: 500,
                width: "100%",
                marginRight: "0px",
                marginLeft: "0px",
            }}
        >
            <g className="plot-area" />
            <g className="x-axis" />
            <g className="y-axis" />
        </svg>
    );
}

export default BarChartD3;

chartcomponent

import React from "react";
import * as d3 from "d3";
import PropTypes from "prop-types";
import { useCubeQuery } from "@cubejs-client/react";
import { Spin, Row, Col, Statistic, Table } from "antd";
import {
  CartesianGrid,
  PieChart,
  Pie,
  Cell,
  AreaChart,
  Area,
  ZAxis,
  XAxis,
  Scatter,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  Legend,
  BarChart,
  ScatterChart,
  Bar,
  LineChart,
  Line
} from "recharts";
import PieSVG from './PieSVG'
import styled from 'styled-components';

import "./recharts-theme.less";
import moment from "moment";
import numeral from "numeral";
import PieChartD3 from "./pieChartd3";
import PieHooks from "./pieHooks";
import BarChartData from './BarChartData';
import BarChartD3 from './BarChart';
import BubbleChartData from './BubbleChartData';
import TreemapD3 from "./TreeContainer";
// import {Treemap} from './Treemap';
import LineChartD3 from './LineChart';
// import BarChartD3 from './BarChart';

const numberFormatter = item => numeral(item).format("0,0");
const dateFormatter = item => moment(item).format("MMM YY");
const colors = ["#7DB3FF", "#49457B", "#FF7C78"];
const xAxisFormatter = (item) => {
  if (moment(item).isValid()) {
    return dateFormatter(item)
  } else {
    return item;
  }
}
const CartesianChart = ({ resultSet, children, ChartComponent, height }) => (
  <ResponsiveContainer width="100%" height={height}>
    <ChartComponent margin={{ left: -10 }} data={resultSet.chartPivot()}>
      <XAxis axisLine={false} tickLine={false} tickFormatter={xAxisFormatter} dataKey="x" minTickGap={20} />
      <YAxis axisLine={false} tickLine={false} tickFormatter={numberFormatter} />
      <CartesianGrid vertical={false} />
      {children}
      <Legend />
      <Tooltip labelFormatter={dateFormatter} formatter={numberFormatter} />
    </ChartComponent>
  </ResponsiveContainer>
)

const TypeToChartComponent = {
  line: ({ resultSet, height }) => (
    <CartesianChart resultSet={resultSet} height={height} ChartComponent={LineChart}>
      {resultSet.seriesNames().map((series, i) => (
        <Line
          key={series.key}
          stackId="a"
          dataKey={series.key}
          name={series.title}
          stroke={colors[i]}
        />
      ))}
    </CartesianChart>
  ),
  bar: ({ resultSet, height }) => (
    <CartesianChart resultSet={resultSet} height={height} ChartComponent={BarChart}>
      {resultSet.seriesNames().map((series, i) => (
        <Bar
          key={series.key}
          stackId="a"
          dataKey={series.key}
          name={series.title}
          fill={colors[i]}
        />
      ))}
    </CartesianChart>
  ),
  area: ({ resultSet, height }) => (
    <CartesianChart resultSet={resultSet} height={height} ChartComponent={AreaChart}>
      {resultSet.seriesNames().map((series, i) => (
        <Area
          key={series.key}
          stackId="a"
          dataKey={series.key}
          name={series.title}
          stroke={colors[i]}
          fill={colors[i]}
        />
      ))}
    </CartesianChart>
  ),
  pie: ({ resultSet, height }) => (
    <ResponsiveContainer width="100%" height={height}>
      <PieChart>
        <Pie
          isAnimationActive={false}
          data={resultSet.chartPivot()}
          nameKey="x"
          dataKey={resultSet.seriesNames()[0].key}
          fill="#8884d8"
        >
          {resultSet.chartPivot().map((e, index) => (
            <Cell key={index} fill={colors[index % colors.length]} />
          ))}
        </Pie>
        <Legend />
        <Tooltip />
      </PieChart>
    </ResponsiveContainer>
  ),
  table: ({ resultSet }) => (
    <Table
      pagination={false}
      columns={resultSet.tableColumns().map(c => ({ ...c, dataIndex: c.key }))}
      dataSource={resultSet.tablePivot()}
    />
  ),
  number: ({ resultSet }) => (
    <Row
      type="flex"
      justify="center"
      align="middle"
      style={{
        height: "100%"
      }}
    >
      <Col>
        {resultSet.seriesNames().map(s => (
          <Statistic value={resultSet.totalRow()[s.key]} />
        ))}
      </Col>
    </Row>
  ),
  bubble: ({ resultSet, height }) => (
    <CartesianChart resultSet={resultSet} height={height} ChartComponent={ScatterChart}>
      {resultSet.seriesNames().map((series, i) => (
        <Scatter
          key={series.key}
          stackId="a"
          dataKey={series.key}
          name={series.title}
          stroke={colors[i]}
        />
      ))}
    </CartesianChart>
  ),
  // pied3: ({ resultSet,height }) => (
  //   <CartesianChart resultSet={resultSet} height={height} ChartComponent={PieSVG}>
  //     {resultSet.seriesNames().map((series, i) => (
  //       <PieSVG
  //       data={data}
  //       width={200}
  //       height={200}
  //       innerRadius={60}
  //       outerRadius={100}
  //     />
  //     ))}
  //   </CartesianChart>
  // ),
  // pied3:({ resultSet,height,}) => (
  //   <ResponsiveContainer width="100%" height={height}>
  //   <PieSVG
  //       data={resultSet.chartPivot()}
  //       dataKey={resultSet.seriesNames()[0].key}
  //     />
  //     </ResponsiveContainer>
  // ),
  pied3: ({ resultSet, height }) => (
    <ResponsiveContainer width="100%" height={height}>
      <PieChartD3 data={[40, 100]}


      // key={resultSet.seriesNames()[0].key}
      />
    </ResponsiveContainer>
  ),
  // bard3:({ resultSet, height }) => (
  //   <CartesianChart resultSet={resultSet} height={height} ChartComponent={BarChartData}>
  //     {resultSet.seriesNames().map((series, i) => (
  //       <BarChartData />
  //     ))}
  //   </CartesianChart>
  // ),
  bard3: ({ resultSet, height }) => (
    <ResponsiveContainer width="100%" height={height}>
      <BarChartD3 data={resultSet.loadResponse.data} />
    </ResponsiveContainer>
  ),
  bubbled3: ({ resultSet, height }) => (
    <ResponsiveContainer width="100%" height={height}>
      <BubbleChartData />
    </ResponsiveContainer>
  ),
  lined3: ({ height }) => (
    <ResponsiveContainer width="100%" height={height}>
      <LineChartD3 />
    </ResponsiveContainer>
  )
  // treed3:({}) => (
  //   <TreemapD3 Graphic={Treemap} url = "https://raw.githubusercontent.com/noe-lc/about-me/master/src/data/product_data.csv"/>
  // )
  // pied3:({resultSet, height}) => (
  //   <ResponsiveContainer width="100%" height={height}>
  //   <PieHooks    
  //         data={[100,200,50,45]}
  //         width={100}
  //         height={height}
  //         innerRadius={0}
  //         outerRadius={100}
  //    />
  //   </ResponsiveContainer>
  // ),
};
const TypeToMemoChartComponent = Object.keys(TypeToChartComponent)
  .map(key => ({
    [key]: React.memo(TypeToChartComponent[key])
  }))
  .reduce((a, b) => ({ ...a, ...b }));

const SpinContainer = styled.div`
  text-align: center;
  padding: 30px 50px;
  margin-top: 30px;
`
const Spinner = () => (
  <SpinContainer>
    <Spin size="large" />
  </SpinContainer>
)


const renderChart = Component => ({ resultSet, error, height }) =>
  (resultSet && <Component height={height} resultSet={resultSet} />) ||
  (error && error.toString()) || <Spinner />;

const ChartRenderer = ({ vizState, chartHeight }) => {
  const { query, chartType } = vizState;
  const component = TypeToMemoChartComponent[chartType];
  const renderProps = useCubeQuery(query);
  return component && renderChart(component)({ height: chartHeight, ...renderProps });
};

ChartRenderer.propTypes = {
  vizState: PropTypes.object,
  cubejsApi: PropTypes.object
};
ChartRenderer.defaultProps = {
  vizState: {},
  chartHeight: 300,
  cubejsApi: null
};
export default ChartRenderer;
0 Answers
Related