John Vasudevan
John Vasudevan

Reputation: 35

Google chart is not rendering properly-React JS

I am new to React js. My requirement is generating graph based on api response. I am using google chart for generating the chart. Please find the code

import React from "react";
import PropTypes from 'prop-types';
import MonitoringDashboardAPI from "../utils/apis/MonitoringDashboardAPI";
import {HTTPStatus} from "../utils/Constants";
import Chart from "react-google-charts";

const cpuMetaData = {names: ['Time', 'System CPU'], types: ['time', 'linear']};
const cpuLineChartConfig = {
    x: 'Time',
    charts: [{type: 'line', y: 'System CPU', style: {markRadius: 2}}],
    gridColor: '#FF0000',
    tipTimeFormat: "%M:%S %Z",
    style: {
        axisLabelColor: '#9c9898',
        legendTitleColor: '#9c9898',
        legendTextColor: '#9c9898',
        tickLabelColor: '#f2f2f2',
    }
};

const styles = {
    root: {display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around'},
    gridList: {height: '50%', overflowY: 'auto', padding: '0 10px', margin: '-10px 0'}
};

const options = {
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" }
};

export default class Dashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isApiCalled: false,
            cpu: [],
            memUsage: [],
            test:[],
            //statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Currently metrics are not available'}),
            isError: false,
            pInterval: 1000,
            interval: 1000
        };
        //this.renderWorkers = this.renderWorkers.bind(this);
         this.renderCPUChart = this.renderCPUChart.bind(this);
    }

    initAutoSync() {
        let interval = '';
        let that = this;
        let queryParams = {
            params: {
                period: '5sec'
            }
        };

        interval = setInterval(() => {
            // that.setState({currentTime: new Date().getTime()});
            MonitoringDashboardAPI.getSystemDetails()
                .then((response) => {
                  // this.state.memUsage.push(Math.floor(Date.now() / 1000),response.data.healthDeterminer.memoryUsage);
                    this.setState({
                        cpu: response.data.healthDeterminer.cpuUsage,
                        memUsage: response.data.healthDeterminer.memoryUsage,
                    });
                   // this.state.memUsage.push(response.data.healthDeterminer.memoryUsage)
                }).catch((error) => {
            });

        }, parseInt(this.state.pInterval));
        this.setState({interval: interval});

    }


    componentDidMount()
     {
       MonitoringDashboardAPI.getSystemDetails()
            .then((response) => {
                if (response.status === HTTPStatus.OK) {
                    this.setState({
                        cpu: response.data.healthDeterminer.cpuUsage,
                        memUsage: response.data.healthDeterminer.memoryUsage,
                        isApiCalled: true,
                        //   statusMessage: response.data === null ? this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Currently metrics are not available'}) : ''
                    });
                }
            }).catch((error) => {
            if (error.response.status === 401) {
                this.setState({
                    isApiCalled: true,
                    //  statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'Authentication failed. Please login again'})
                });
            } else if (error.response.status === 403) {
                this.setState({
                    isApiCalled: true,
                    // statusMessage: this.context.intl.formatMessage({id:'systemDetails', defaultMessage:'User have no permission to view this page'})
                });
            } else {
                this.setState({
                    isError: true,
                    isApiCalled: true,
                    //statusMessage: this.context.intl.formatMessage({id:'unknownError', defaultMessage: 'Unknown error occurred! : {data}', values: { data: JSON.stringify(error.response.data) } })
                });
            }
        });
        clearInterval(this.interval);
        this.initAutoSync();
        console.log(this.state.memUsage)
    }

    renderCPUChart() {
        return (
            <div style={{backgroundColor: '#131313', paddingTop: 10, height: '370px'}}>
                <div style={{backgroundColor: '#131313', paddingTop: 60, height: 255, width: '100%'}}>
                    <h1 style={{color: '#3366cc'}}>{this.state.memUsage} </h1>
                    <div className="App">
                        <Chart
                            chartType="LineChart"
                            width="100%"
                            height="400px"
                            data={[
                                ["Time stamp", "Memory Usage"],
                                [Math.floor(Date.now() / 1000), this.state.memUsage],
                            ]}
                            options={options}
                        />
                    </div>
                </div>
            </div>
        );
    }


    render() {
        console.log(this.state.cpu.length)
        return (
            this.renderCPUChart()
        );
    }
}

initAutoSync() method is used to call api in a particular time period. In 1this example, am calling the api in every 1 second.

My problem is memUsage array always contains only one element even though API is called. But the value is getting updated according to the API response. Basically the values are not appending.It's overwriting the values. So am getting only one point in the chart.

Please find the screenshot of my output

screenshot

Upvotes: 2

Views: 2018

Answers (1)

WhiteHat
WhiteHat

Reputation: 61232

try initializing all of the chart data in componentDidMount...

this.setState({
    chartData: [
        ["Time stamp", "Memory Usage"],
        [Math.floor(Date.now() / 1000), response.data.healthDeterminer.memoryUsage],
    ],
    isApiCalled: true,
});

then append during the interval...

this.state.chartData.push([Math.floor(Date.now() / 1000), response.data.healthDeterminer.memoryUsage]);

and the chart...

<Chart
    chartType="LineChart"
    width="100%"
    height="400px"
    data={this.state.chartData}
    options={options}
/>    

Upvotes: 1

Related Questions