Search code examples
javascriptapexcharts

Check if chart is rendered in apexcharts


I am destroying the chart but when it's not rendered I get error.

Is there a way to check if chart is rendered, then destroy it?

if(chart)
chart.destroy()

Each time i destroy an object that does not exist i get TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

Also i need to render it again if it's not rendered, i won't render it again and again. I need that check


Solution

  • The linked documentation states that render() returns a promise once the chart is drawn to the page.

    The code however seems to return that promise immediately (which makes sense) and resolves that promise, when the chart was drawn. As far as I can see, it should be sufficient to set and keep a state-flag after the promise is resolved like so:

    let chart = new ApexCharts(el, options);
    
    chart.render().then(() => chart.ohYeahThisChartHasBeenRendered = true);
    
    /* ... */
    
    if (chart.ohYeahThisChartHasBeenRendered) {
        chart.destroy();
    }
    

    Update after comment

    Yes this works! I made this runnable example for you (typically this is the duty of the person asking the question ;) ) Press the button and inspect the log):

    <html>
        <head>
            <title>chart test</title>
            <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
        <head>
    
        <body>
    
            <div id="chart"></div>
    
            <script>
                let options = {
                        chart: { type: 'line' },
                        series: [{ name: 'sales', data: [30,40,35,50,49,60,70,91,125] }],
                        xaxis: { categories: [1991,1992,1993,1994,1995,1996,1997, 1998,1999]}
                    },
                    chart = new ApexCharts(document.querySelector("#chart"), options),
                    logChart = () => console.log(chart),
                    destroyChart = () => {
                        if (chart.ohYeahThisChartHasBeenRendered) {
                            chart.destroy();
                            chart.ohYeahThisChartHasBeenRendered = false;
                        }
                    };
    
                chart.render().then(() => chart.ohYeahThisChartHasBeenRendered = true);
    
            </script>
    
            <button onclick="logChart()">Log chart</button>
            <button onclick="destroyChart()">Destroy chart</button>
    
        </body>
    </html>
    

    I suspect that you tried something like this to check for the flag:

    chart.render().then(() => chart.ohYeahThisChartHasBeenRendered = true);
    console.log(chart.ohYeahThisChartHasBeenRendered);
    

    It will not do what you expect because the promise is not resolved yet.

    Update after another comment

    As pointed out by a comment there is a related known issue with apexcharts: https://github.com/apexcharts/apexcharts.js/pull/415