-1

this is my first post, im using Anychart library with React in a component build, i was able to implementing but the way that anychart recomend to use in every render the chart is duplicated. This is my component

const Chart: React.FunctionComponent = () => {

 function charts()  {

    // create data
    const data = [
      {
        x: '2022-07-26',
        y: '0.29822798232939185',
      },
    ];

    // create a chart and set the data
    const chart = anychart.line();
    chart.data(data);

    // set the chart title
    chart.title('Sales of the Most Popular Products of ACME Corp.');

    // set the titles of the axes
    chart.xAxis().title('Year');
    chart.yAxis().title('Revenue');

    // draw
    chart.container('container');
    chart.draw();
  }

  React.useEffect(() => {
    charts();
  }, []);

  return <StyledDiv id="container" />;
};

export default Chart;

As you see, is very simple, but every time the app makes a render this component is duplicated and generate a new chart.

1 Answers1

0

This problem can be solved by returning the chart itself in the charts() function.

 function charts()  {

//your code here 

 // draw
    chart.container('container');
    chart.draw();
//returning chart variable
        return chart
}

Then chart.dispose() function must then be returned in a useEffect hook.

useEffect(() => {
    const chart = charts();

    // Return a cleanup function to remove the chart when the component unmounts
    return () => chart.dispose();
  }, []);

This problem appears due to React LifeCycle, and it can be solved by deleting duplicates when it has been rendered, which is what the dispose function does. You can use the example of the dispose function, which prevents duplicates in React.

AnyChart Support
  • 3,770
  • 1
  • 10
  • 16