Integrating Google Charts

I’m trying to integrate google-charts with Stimulus.
I used, as a starting point, https://www.npmjs.com/package/google-charts#quick-start and I have looked at https://glitch.com/edit/#!/stimulus-highcharts?path=src/controllers/chart_controller.js

My controller looks like

import { Controller } from "stimulus"
import { GoogleCharts } from 'google-charts'

export default class extends Controller {
  connect() {
    GoogleCharts.load(this.drawChart())
  }

  drawChart() {
    const data = GoogleCharts.api.visualization.arrayToDataTable([
            ['Chart thing', 'Chart amount'],
            ['Lorem ipsum', 60],
            ['Dolor sit', 22],
            ['Sit amet', 18]
          ])
    const pie_1_chart = new GoogleCharts.api.visualization.PieChart(document.getElementById('chart_div'))
    pie_1_chart.draw(data)
  }
}

But I get TypeError: "__WEBPACK_IMPORTED_MODULE_1_google_charts__.a.api is undefined"

Am I missing anything here?

Thanks.

The GoogleCharts.load API takes a function as an argument, where you are passing in the return value of your function instead.

Notice how they pass the function by value in the documentation, instead of invoking it:

// Good
GoogleCharts.load(drawChart);

// Bad
GoogleCharts.load(drawChart());

If you replace:

connect() {
  GoogleCharts.load(this.drawChart())
}

with:

connect() {
  GoogleCharts.load(this.drawChart.bind(this))
}

it should work just fine :slight_smile:

I’ve added the bind(this) part because your function belongs to an instance of a class (the Stimulus controller), and it needs to keep its bindings to that instance, when the Google Charts API calls it. This way you can still reference members of the class inside the callback function.

2 Likes

It does. Thanks for the explanation.

1 Like