Home > OS >  How can I stop the function get executed two times?
How can I stop the function get executed two times?

Time:06-28

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

CodePudding user response:

If you are using React v18 then useEffect runs twice in development and strict modes; and this is done by design.

CodePudding user response:

This is development mode behavior. Useeffect runs twice in dev mode. You will not get the same behaviour in production. If you want to remove this effect, you should remove the React.StrictMode that your app component is wrapped

  • Related