Stimulus Discourse

Integrating Google Charts


I’m trying to integrate google-charts with Stimulus.
I used, as a starting point, and I have looked at!/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() {

  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'))

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

Am I missing anything here?



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

// Bad

If you replace:

connect() {


connect() {

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.

1 Like

It does. Thanks for the explanation.

1 Like