next.jsapexchartsreact-apexcharts

Unable to update pie chart


I am using nextjs 15.2.5, apexcharts 4.7.0 and react-apexcharts 1.7.0

With below code i try to update a pie chart without luck. I tried 2 different options as they are shown in the docs and elsewhere. Would anybody be so kind an tell what's wrong with this code?

"use client"
import ApexCharts, { ApexOptions } from "apexcharts";
import { useEffect, useState } from "react";
import Chart from 'react-apexcharts';

var initialOptions: ApexOptions = {
  chart: {
    id: "my-pie",
    width: 380,
    type: 'pie',
  },
  series: [44, 55, 13, 43, 22],
  labels: ['Team A', 'Team B', 'Team C', 'Team D', 'Team E'],
};

const ApexPieChartChangeView = () => {

      const [state, setState] = useState(initialOptions)

      const onChangeSeries1 = () => {
        const newLabels = ['Member A', 'Member B', 'Member C', 'Member D', 'Member E']
        const newSeries = [10, 30, 40, 5, 15]
        setState(prev => {
          return {...prev, labels: newLabels, series: newSeries }
        })
      }

      const onChangeSeries2 = () => {
        const newLabels = ['Member A', 'Member B', 'Member C', 'Member D', 'Member E']
        const newSeries = [10, 30, 40, 5, 15]
        ApexCharts.exec("my-pie", "updateOptions",  {...initialOptions, labels: newLabels, series: newSeries }, true)
      }

      useEffect(() => {
        console.log(`ApexPieChartChangeView on state changed ${JSON.stringify(state.labels)}`) //this is printed out each time onChangeSeries1 was called
      },[state])

      return (
        <div>    
          <Chart
              options={state}
              series={state.series}
              type="pie"
              width="500"  
          />
          <button onClick={onChangeSeries1}>Change series 1</button>
          <button onClick={onChangeSeries2}>Change series 2</button>
        </div> 
      )
}

The component is then dynamically imported like below (which is necessary when using apexcharts with nextjs next otherwise we get window not defined error)

import dynamic from 'next/dynamic'

const ApexPieChartChangeView = dynamic(() => import('./ApexPieChartChangeView'), { ssr: false });

Solution

  • Your issue is due to how react-apexcharts expects props structure: