Skip to content

[Chart.js] Stimulus connect is called multiple time causing errors #1408

@Shadow-Devil

Description

@Shadow-Devil

I'm using Google's Material Design Lite which causes the canvas elements to be disconnected and later reconnected.

This causes to recreate a second Chart but with the same element, causing an error:

> symfony--ux-chartjs--chart #initialize
> symfony--ux-chartjs--chart #connect
> application #start
> symfony--ux-chartjs--chart #disconnect
> Error connecting controller
Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused.

There could be two possible fixes I can think of:

  • Adding a check in the connect method if the canvas already has a chart, e.g. if(Chart.getChart(this.element)) and only if there is none create the Chart
  • Destroying the chart on disconnect, e.g. this.chart.destroy()

Relevant Code:
https://github.com/symfony/ux-chartjs/blob/2.x/assets/src/controller.ts#L52
https://github.com/chartjs/Chart.js/blob/master/src/core/core.controller.js#L141-L150

References:
https://stimulus.hotwired.dev/reference/lifecycle-callbacks
https://www.chartjs.org/docs/latest/developers/api.html#static-getchart-key
https://www.chartjs.org/docs/latest/developers/api.html#destroy

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions