Search code examples
highchartsreact-highchartsno-data

noData value not updating when the state changes in React


I have a state which holds the chart option. In that config I initialised value of noData with a value (actually wanted to initialise with an empty string to avoid showing "No data to display" for a moment before the original data gets plotted. But initialised with another value to illustrate the issue).

And in the useEffect I set the actual chart option with series data and other props values.

Actual behaviour When there is no data, chart shows the initial value of noData. It should show the updated value.

Live demo with steps to reproduce https://codesandbox.io/s/cool-tesla-pqzqdd?file=/src/App.js

Product version Highcharts - 10.3.2

The primary goal is to avoid showing "No data to display" during the initial render

import { useEffect, useState } from "react";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";
import drilldown from "highcharts/modules/drilldown.js";
import NoDataToDisplay from "highcharts/modules/no-data-to-display";

drilldown(Highcharts);
NoDataToDisplay(Highcharts);

const App = () => {
  const [chartOption, setChartOption] = useState({
    chart: {
      backgroundColor: "transparent",
      height: 350
    },
    title: { text: "" },
    credits: {
      enabled: false
    },
    accessibility: {
      enabled: false
    },
    lang: {
      noData: "Initial value of noData"
    }
  });

  useEffect(() => {
    setChartData();
  }, []);

  const setChartData = () => {
    const options = {
      chart: {
        type: "line",
        backgroundColor: "transparent",
        height: 350,
        animation: false
      },
      credits: {
        enabled: false
      },
      accessibility: {
        enabled: false
      },
      lang: {
        noData: "No data to display"
      },
      yAxis: {
        gridLineColor: "transparent"
      },
      series: []
    };
    setChartOption(options);
  };

  return <HighchartsReact options={chartOption} highcharts={Highcharts} />;
};

export default App;

When there is no data, chart should show the updated value of noData. The state value is getting updated correctly, but chart isn't.


Solution

  • The lang options are global and can not be changed during the update.

    As a solution, you can update the global options through setOptions and enable the immutable option.

    Highcharts.setOptions({
      lang: {
        noData: "No data to display"
      }
    });
    

    Alternatively, you can display the whole component only if data is received, like here.


    Live demo: https://codesandbox.io/s/festive-curie-wryzl-wryzlc?file=/src/App.js

    API Reference: https://api.highcharts.com/highcharts/lang