import React from 'react'
import ReactApexChart from 'react-apexcharts'
import ApexCharts from 'apexcharts'
import './styles.css'

var TICKINTERVAL = 1000
var XAXISRANGE = 29 * TICKINTERVAL
var lastX = new Date().getTime() - XAXISRANGE
var lastY = 50
var data = []

function nextValue() {
  lastY = Math.max(5, Math.min(95, lastY + (Math.random() - 0.5) * 20))
  return Math.round(lastY)
}

while (data.length < 30) {
  data.push({ x: lastX, y: nextValue() })
  lastX += TICKINTERVAL
}

const ApexChart = () => {
  const [state, setState] = React.useState({
    series: [
      {
        name: 'Signal',
        data: data.slice(),
      },
    ],
    options: {
      chart: {
        id: 'realtime-streaming',
        height: 350,
        type: 'line',
        streaming: {
          enabled: true,
        },
        animations: {
          dynamicAnimation: {
            speed: 1000,
          },
        },
        toolbar: {
          show: false,
        },
        zoom: {
          enabled: false,
        },
      },
      dataLabels: {
        enabled: false,
      },
      stroke: {
        curve: 'smooth',
      },
      title: {
        text: 'Streaming (bounded memory + linear scroll)',
        align: 'left',
      },
      markers: {
        size: 0,
      },
      xaxis: {
        type: 'datetime',
        range: XAXISRANGE,
      },
      yaxis: {
        min: 0,
        max: 100,
      },
      legend: {
        show: false,
      },
    },
  })

  React.useEffect(() => {
    const interval = window.setInterval(() => {
      lastX += TICKINTERVAL
      ApexCharts.exec('realtime-streaming', 'appendData', [
        {
          data: [{ x: lastX, y: nextValue() }],
        },
      ])
    }, TICKINTERVAL)
    return () => window.clearInterval(interval)
  }, [])

  return (
    <div>
      <div id="chart">
        <ReactApexChart
          options={state.options}
          series={state.series}
          type="line"
          height={350}
        />
      </div>

      <div className="explanation">
        Real-time streaming with <code>chart.streaming.enabled</code>: each tick
        appends one point with <code>appendData()</code>. The window slides left
        at constant velocity (no easing pulse, no in-place warp), and the series
        array is trimmed automatically to the visible <code>xaxis.range</code>{' '}
        window, so memory stays flat no matter how long the stream runs. The
        same scroll works when a fixed-length rolling window is passed to{' '}
        <code>updateSeries()</code>.
      </div>
    </div>
  )
}

export default ApexChart
Realtime - React Line Charts | ApexCharts.js | ApexCharts.js