pyroCoder
pyroCoder

Reputation: 170

'Dashboard not a constructor' error with Google Charts

I am a naive React Developer and facing some difficulty with getting gooogle chart work with react. I am using Google Charts in a ReactJs component with ControlWrapper as shown below.

componentDidMount: function(){
google.charts.load('current', {'packages':['corechart', 'controls']});
this.drawCharts();
},
componentDidUpdate: function(){
 google.charts.load('current', {'packages':['corechart', 'controls']});
this.drawCharts();
},
drawCharts: function(){
var cmpt = this;
//Removed detailed code from here due to copyright issues

//adding controls----------------
  
  let dashboard = new google.visualization.Dashboard( document.getElementById(cmpt.props.widgetId) );
  let controlId = '${this.props.widgetId}_control';
  var controlWrapper = new google.visualization.ControlWrapper({
    'controlType' : 'NumberRangeFilter',
    'containerId' : controlId,
    'options' : {
      'filterColumnLabel' : xDataSysName
    }
  });
  var barChart = new google.visualization.ChartWrapper({
    'chartType': 'BarChart',
    'containerId': this.props.widgetId,
    'options': options
  });

  dashboard.bind(controlWrapper, barChart);
  dashboard.draw(data);

  if(linkColumn){
    let selectionEventHandler = function() {
      window.location = data.getValue(barChart.getSelection()[0]['row'], 1 );
    };
      google.visualization.events.addListener(barChart, 'select', selectionEventHandler);
   }
  }
},

This is not the whole piece of code but should be enough for the issue I'm facing.

First time I load the page, I get the error in the console saying

google.visualization.Dashboard is not a constructor

I reload the page hitting SHIFT+F5, the error goes away and components load just fine except ones that are dependent on controlWrapper throwing the error as follows

google.visualization.controlWrapper is not a constructor

which never goes away even after reloading the page. I referred to this discussion and tried their solution but I am still getting these error in the manner mentioned above. Please help me figure out how to fix it. Also, I am not able to comprehend why dashboard error goes away on a reload.

Upvotes: 1

Views: 290

Answers (1)

WhiteHat
WhiteHat

Reputation: 61222

need to wait until google charts has fully loaded before trying to use any constructors,
this is done by providing a callback function.

try changing the load statement as follows...

componentDidMount: function(){
  google.charts.load('current', {packages:['corechart', 'controls'], callback: this.drawCharts});
},
componentDidUpdate: function(){
  google.charts.load('current', {packages:['corechart', 'controls'], callback: this.drawCharts});
},

Upvotes: 1

Related Questions