0

I created code in React and I want to increment goals by 1 after click on div. But I got invalid output like this:

props.goals = 1

... clicked div and executing function addGoal.

From console log: BEFORE From console log: 1

setstateStatistics executing

From console log: AFTER From console log: 1 //HERE IS BAD OUTPUT - should be 2.

... again clicked div ...

From console log: BEFORE From console log: 2

setstateStatistics executing

From console log: AFTER From console log: 2 //HERE IS BAD OUTPUT - should be 3.

Props values are correct includes h2 tags in return {stateStatistics.goals} value. Please can you help me with this problem?

import React, { useState } from 'react';

import './StatisticItem.css';
import Card from '../../shared/UIElements/Card';


const StatisticItem = props => {

    const [stateStatistics, setstateStatistics] = useState({
        name: props.name,
        goals: props.goals
    });



    const addGoal = async event => {
        event.preventDefault();

        console.log("BEFORE ");
        console.log(stateStatistics.goals);

        setstateStatistics({
           name: stateStatistics.name,
           goals: stateStatistics.goals+1
        });    

        console.log("AFTER ");
        console.log(stateStatistics.goals);
}


return (
        <div>
            <li className="statistic-item">
                <Card className="statistic-item__content">
                    <div className="statistic-item__info">
                        <h2>{stateStatistics.name}</h2>
                    </div>
                </Card>
            </li>
            <li className="statistic-item" onClick={addGoal}>
                <Card className="statistic-item__content">
                    <div className="statistic-item__info">
                        <h2>{stateStatistics.goals}</h2>
                    </div>
                </Card>
            </li>

        </div>
    );
};

export default StatisticItem;
Johan Does
  • 17
  • 4

0 Answers0