I have this component which should display some data in a graph.
I would like to execute the updateChart function at first and everytime userData.transactions change (so I can populate the chart with updated datas).
Everything seems to work properly, but at the beginning it execute two times, so it also push inside the dataset the same datas two times...
How can I solve this? Thanks in advance!
That's the component code
import React from 'react' import {useEffect } from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler, } from 'chart.js'; import { Line } from 'react-chartjs-2'; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler ); export const options = { responsive: true, plugins: { legend: { position: 'top', }, title: { display: true, text: 'Chart.js Line Chart', }, }, }; const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; export const data = { labels, datasets: [ { fill: true, label: 'Dataset 1', data: [], borderColor: 'rgb(53, 162, 235)', backgroundColor: 'rgba(53, 162, 235, 0.5)', }, ], }; const ChartHistory = ({userData}) => { const updateChart = () => { const amounts = data.datasets[0].data for (let i = 0; i < userData.transactions.length; i++) { amounts.push(userData.transactions[i].amount) } } useEffect(() => { updateChart() }, [userData.transactions]) return ( <div> <Line options={options} data={data} /> </div> ) } export default ChartHistory