Search code examples
chart.jsblazor-webassembly

How to reuse a Chart.js chart in Blazor wasm?


How to reuse a Chart.js chart in Blazor wasm? I got the error message to destroy the canvas before reuseing. I read this topic: Destroy chart.js bar graph to redraw other graph in same <canvas> But none of these answers solved my problem. This is my method to invoke the JavaScript of Chart.js

await JSRuntime.InvokeVoidAsync("setup", Id, config);

window.setup = (id, config) => {
    var ctx = document.getElementById(id).getContext('2d');
    new Chart(ctx, config);
}

How can I implement a working .destroy() call in the method, or how can I update the chart?


Solution

  • Got it:

    window.setup = (id, config) => {
    
        var myChart = Chart.getChart(id);
    
        if (myChart != undefined) {
            myChart.destroy();
        }
    
        var ctx = document.getElementById(id).getContext('2d');
        new Chart(ctx, config);
    
        console.log(config);
    }
    

    (First it was not working for reasons of the browsers cache)