apexcharts / apexcharts.js

📊 Interactive JavaScript Charts built on SVG
https://apexcharts.com
MIT License
14.08k stars 1.27k forks source link

Keeping the zoom level after updating the data #2349

Closed SWi98 closed 3 years ago

SWi98 commented 3 years ago

I want to create a candlestick chart in React with data being updated a few times every second. The problem starts when I navigate the chart and then the update fires. What happens is, the chart gets completely rerendered and the current zoom level is reset to the default value. With updates being conducted a few times every second navigating gets pretty much impossible. Is it possible to update the chart with new data, but keep the current zoom level?

AMATEURTOSS commented 2 years ago

i have same question do you have solution??

icefee commented 2 years ago

share my solution.


const range = React.useRef(null)
const needSetZoom = React.useRef(false)

React.useEffect(() => {
   if (range.current) {
       needSetZoom.current = true;
    }
}, [data]) // data changed

const chartOption = {
   chart: {
      events: {
          zoomed: function (_chartContext, { xaxis }) {
             range.current = xaxis;
          },
          scrolled: function (_chartContext, { xaxis }) {
              range.current = xaxis;
          },
          updated: function (context) {
              if (needSetZoom.current) {
                   const { min, max } = range.current;
                   context.zoomX(min, max);
                   needSetZoom.current = false;
               }
          }
      }
   }
}