Skip to content
Advertisement

React useState throws error on Highcharts mouseOver

I have a react typescript app with a highcharts chart. I want to update a “price” label (outside of the highcart) based on the data I get when a user is hovering their mouse over part of the chart.

The mouseOver callback is working fine, and I can successfully log the data I want to the console. But when I try to update the state of price using the useState hook for setPrice I get an error from highcharts. If I comment the setPrice line out, no errors. Any thoughts?

Uncaught TypeError: Cannot read properties of null (reading 'yAxis')
    at highstock.src.js:24009
    at Array.forEach (<anonymous>)
    at c.getAnchor (highstock.src.js:23992)
    at c.refresh (highstock.src.js:24517)
    at c.runPointActions (highstock.src.js:27941)
    at c.onContainerMouseMove (highstock.src.js:27502)

Here’s some pseudo code for how i’ve implemented it:

const [price, setPrice] = useState<number>(0)

options = {
  ...
  plotOptions: {
    series: {
      point: {
        events: {
          mouseOver: function(e:any) {
            price = // logic to fetch price based on mouse position 
            console.log(price)   
            setPrice(price)
          }
        }
      }    
    }
  }
}

And the html (styled-components)

<Price>{ price }</Price>

Advertisement

Answer

The data isn’t probably available immediately that’s why it’s returning a null data. However, you can set the data asynchronously using a setTimeout delay like so.

const [price, setPrice] = useState<number>(0)

options = {
  ...
  plotOptions: {
    series: {
      point: {
        events: {
          mouseOver: function(e:any) {
            price = // logic to fetch price based on mouse position 
            console.log(price)   
            setTimeout(() => { // This is where the delay comes in
            setPrice(price)
            }, 0)
          }
        }
      }    
    }
  }
}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement