Search code examples
reactjshighchartsreact-highcharts

Adding series to highchart and remove loading without creating new chart


I'm using Highchart with React.

For the moment I created a starting options:

/**
  * Initial chart options, with "loading" enabled
  */
  const chartOptions = {
    accessibility: {
      enabled: false
    },
    chart: {
      type: "column",
      events: {
        load() {
          const chart = this;
          chart.showLoading(`${LOADING}...`);
        }
      }
    }
  };

In that component I call an API that returns some data to use. So, at that moment, I want to remove the "loading" and adding the data.

I solved for the moment with:

const [options, setOptions] = useState(chartOptions);

useEffect(() => {
    if (detail) {
      setOptions({
        ...chartOptions,
        chart: {
          type: "column"
        },
        xAxis: {
          categories: detail.map(
            (item) =>
              `${item.data_em.substring(4, 6)}/${item.data_em.substring(0, 4)}`
          )
        },
        series: [
          {
            name: "Alfa",
            color: "#69BC66",
            data: detail.map((item) => item.ricevuti)
          },
          {
            name: "Beta",
            color: "#DC3545",
            data: detail.map((item) => item.mancanti)
          },
        ]
      });
    }
  }, [detail]);


<ChartComponent options={options} />

So, setting a new options in local State when data are ready. But I imagine that in this manner I get a different chart.

It works, but is there a better method?


Solution

  • With using the highcharts-react-official wrapper, the chart is recreated on state update only if immutable option is enabled. Otherwise, only chart.update method is called to apply changes.

    Therefore, it is better to apply only the new options. In your case it will be:

    useEffect(() => {
      if (detail) {
        setOptions({
          chart: {
            type: "column"
          },
          xAxis: {
            categories: detail.map(
              (item) =>
              `${item.data_em.substring(4, 6)}/${item.data_em.substring(0, 4)}`
            )
          },
          series: [{
              name: "Alfa",
              color: "#69BC66",
              data: detail.map((item) => item.ricevuti)
            },
            {
              name: "Beta",
              color: "#DC3545",
              data: detail.map((item) => item.mancanti)
            },
          ]
        });
      }
    }, [detail]);
    

    Live demo: https://codesandbox.io/s/highcharts-react-demo-3lvomg?file=/demo.jsx

    Docs: https://www.npmjs.com/package/highcharts-react-official#optimal-way-to-update