Update chart with HighchartsReact is not working when a timer is used in React

Viewed 180

I have the code to show data on my page using Highchart and React

  var chart_nps_amigo = {
    title: { text: '% Alunos x total de horas de acesso' },
    chart: { height: 200, type: 'column' },
    xAxis: {
      type: 'category',
      labels: {
          rotation: -45,
          style: {
              fontSize: '13px',
              fontFamily: 'Verdana, sans-serif'
          }
      }
    },
    yAxis: {
        title: { text: 'Número de alunos' }
    },
    tooltip: {
        pointFormat: 'Porcentagem: <b>{point.y:.1f} alunos</b>'
    },
    series: [{
      name: 'Alunos',
      data: [
          ['Nunca acessou', 24.2],
          ['Até 4h', 10.8], 
          ['Até 8h', 22.5], 
          ['Até 12h', 11],
          ['Até 16h', 9.3],
          ['Mais de 16h', 4.8]
      ],
      dataLabels: {
          enabled:   true,
          align: 'center',
          format: '{point.y:.1f}', // one decimal
          y: 10, 
          style: {
              fontSize: '11px',
              fontFamily: 'Verdana, sans-serif'
          }
      }
    }]

  }

I can use the following code to show the chart in my page

<HighchartsReact
          highcharts={Highcharts}
          options={chart_nps_amigo}
          allowChartUpdate={true}
        />

With the code below I was able to update the charts

      chart_nps_amigo.series[0].data.push( ['32h v1', 55] );

but I wanna update the chart with values that are coming from a web server using Redux and Redux-Saga.

To simulate that, I just create a timer event to update the chart using the following code:

const timer = setTimeout(() => {
  chart_nps_amigo.series[0].data.push( ['32h v2', 24.8] );
  console.log('This will run after 10 second!')
}, 10000);

But after 10 seconds, the log code shows in the browser console, but the chart is not updated.

How can I make this work ?

2 Answers

I find a solution now. Based in the answer of @SebastianWędzel

The way that I describe data previously, it was an array in javascript, but it's not a valid json object.

series: [{
  name: 'Alunos',
  data: [
      ['Nunca acessou', 24.2],
      ['Até 4h', 10.8], 
      ['Até 8h', 22.5], 
      ['Até 12h', 11],
      ['Até 16h', 9.3],
      ['Mais de 16h', 4.8]
  ],

But since I recover this value from a web server using redux and redux-saga, I need a way to add a valid Json object.

When I look in the Highcharts documentation, I find another way to show the series data using a valid Json object

series: [{
  name: 'Alunos',
  data: [{
    "name": "Nunca acessou",
    "y": 24.2
  }, {
    "name": "Até 4h",
    "y": 10.8
  }],      

Now I attach the value that I get from the web server only to the series data part of the chart

series: [{
  name: 'Alunos',
  data: chart.myData,
  

It's working now.

Related