margelo / react-native-graph

📈 Beautiful, high-performance Graphs and Charts for React Native built with Skia
https://margelo.io
MIT License
2.08k stars 118 forks source link

Cannot read property 'date' of undefined when range is too large #95

Open Savinvadim1312 opened 10 months ago

Savinvadim1312 commented 10 months ago

Description

When the X range is too large, it throws the error

Cannot read property 'date' of undefined 

Minimal reproducible repo

https://github.com/Savinvadim1312/ReactNativeGraphTest

Code example:

export default function App() {
  const points: GraphPoint[] = [
    {
      date: new Date(2024, 1, 1),
      value: 10,
    },
    {
      date: new Date(2024, 2, 1),
      value: 100,
    },
  ];

  const goodRange = {
    x: {
      min: new Date(2024, 1, 1),
      max: new Date(2025, 1, 1),
    },
  };

  const badRange = {
    x: {
      min: new Date(2024, 1, 1),
      max: new Date(2070, 2, 1),
    },
  };

  return (
    <LineGraph
      points={points}
      range={badRange}
      animated={false}
      color="#4484B2"
      style={styles.graph}
    />
  );
}

Investigation

The problem seems to be inside the getGraphDataIndex function from CreateGraphPath.ts file:

  const getGraphDataIndex = (pixel: number) =>
    Math.round(((pixel - startX) / (endX - startX)) * (graphData.length - 1))

Because the range is too large, endX and startX end up being equal, and the above function divides by 0. In that case, this function returns NaN and then when used as an index, leads to the Cannot read property 'date' of undefined