import {gql, useLazyQuery} from '@apollo/client'; import {Spinner, Stack, Text} from '@chakra-ui/react'; import {snakeCase} from 'change-case'; import React, {useEffect, useState} from 'react'; import {Bar, BarChart, CartesianGrid, Cell, Legend, Tooltip, XAxis, YAxis} from 'recharts'; export interface BarComponentProps { componentName: string, title?: string, titleFontColor?: string, titleFontSize?: string, titleFontWeight?: string, table_name: string, data_columns: string[], orientation?: string, showLegend?: boolean, width: number, height: number, barsColor: string, } function BarChartComponent(props: BarComponentProps) { const { title, titleFontColor = "black", titleFontSize = "18px", titleFontWeight = "500", table_name = "", data_columns, orientation, showLegend = true, width, height, barsColor } = props; const [barContent, setBarContent] = useState([ { name: '', value: 0 } ]); useEffect(() => { if (data_columns.length >= 2) { fetchData() } else { console.log("Not enough data columns"); } }, [data_columns]); let q = gql` query { ${snakeCase(table_name)} { ${data_columns.map(col => `${col}`).join(',')} } }`; const [fetchData, { loading, error }] = useLazyQuery(q, { onCompleted: (res) => { let mData = [...res[snakeCase(table_name)]]; // sort array in descending order by value mData.sort((a, b) => (a.value < b.value) ? 1 : -1); setBarContent(mData); }, onError: (error) => { console.log(error); } }); function isVertical() { return orientation === "vertical"; } return ( {title} {loading ? : error ? {error.message} : data_columns.length < 2 ? Not enough data columns (required: 2) : isVertical() ? {showLegend && } {barContent.map((d, idx) => { return ; })} : {showLegend && } } ); } export default BarChartComponent;