0

I'm trying to debounce the method call: "chart.calculateChartData(props.answers)".

I tried: - autorun - reaction - use-debounce from a react lib. - setTimeout within calculateChartData

Each solution led to an update cycle or didn't work because MobX is not immutable.

Has someone a hint?

function QuantificationChart(props: QuantificationChartProps) {
    const {t} = useTranslation();

    const rootStore = useRootStore();
    const chart = rootStore.formulaStore.getChart<Chart>(Chart.chartName);
    const data = chart.calculateChartData(props.answers);
calculateChartData = (questionData: { [id: string]: number; } = {}) => {
        let chartData = [];
        for (let i = 0; i < this.numberOfYears + 1; ++i) {
            let customData = {...questionData, "year" : i};
            let chartEntry = {
                cost: this.rootStore.formulaStore.calculateFormula(this.cost.formula, customData),
                earn: this.rootStore.formulaStore.calculateFormula(this.earn.formula, customData),
                sum: 0
            };
            chartEntry.sum = (chartEntry.earn - chartEntry.cost) + (chartData[i - 1]?.sum || 0);
            chartData.push(chartEntry);
        }
        return chartData;
    };

Hint: It's my first project with MobX

im4ever
  • 469
  • 1
  • 4
  • 14

1 Answers1

0

Found a solution. Seems to work:

Based on: https://mobx-react.js.org/recipes-effects

    const [data, setData] = React.useState(chart.calculateChartData(props.answers));

    React.useEffect(
        () =>
            autorun(() => {
                setData(chart.calculateChartData(props.answers));
            }, {delay: 1000}),
        [],
    );
im4ever
  • 469
  • 1
  • 4
  • 14