SmarthBansal
SmarthBansal

Reputation: 175

setState does not change state in React in a functional component

Below is my code that I'm trying to run. It is supposed to get input from the user (stored in inputData state). And display the output using resultData. However the result displayed is the default empty inputData values (not the values entered by the user).
The inputData variable is successfully receiving the values from the input fields (confirmed by logging). But the resultData object isn't updating with these values when the onSubmit function is called. I have abstracted some of the code here for convenience.

Further Investigation --
Logging inputData inside onSubmit prints out the initial empty values of inputData
Logging inputData inside MyContainer prints out the correct entered values. Logging resultData anywhere prints out default empty value.

All help is appreciated.

export default function MyContainer() {

    const [inputData, setInputData] = React.useState({
        name1: "",
        name2: "",
        ans: ""
    });
    let resultData = {};
    const [resultVisibility, setResultVisibility] = React.useState(false)

    function handleChange(event) {
        // Changes inputData state by calling setInputData

    }

    function onSubmit() {
        // Calculate resultData based on inputData
        resultData = {
             name1: inputData.name1,
             name2: inputData.name2,
             result: 50

        };

        setResultVisibility(true);
    }

    return (
        <div>
            <MyInputComponent
                name1={inputData.name1}
                name2={inputData.name2}
                ans={inputData.ans}
                onSubmit={onSubmit}
                onChange={handleChange}
            />
            {resultVisibility && <MyResultComponent
                name1={resultData.name1}
                name2={resultData.name2}
                result={resultData.result}
            />}
        </div>
    );
}

Upvotes: 0

Views: 341

Answers (2)

Art Bauer
Art Bauer

Reputation: 489

Use state for resultData:

const [resultData, setResultData] = useState({});

Use useCallback and update resultData on submit:

const onSubmit = useCallback(() => {
    // Calculate resultData based on inputData
    setResultData({
         name1: inputData.name1,
         name2: inputData.name2,
         result: 50

    });

    setResultVisibility(true);
}, [inputData]);

Upvotes: 2

nbsamurai
nbsamurai

Reputation: 346

resultData should be using useState like below

const [resultData, setResultData] = React.useState({
        name1: "",
        name2: "",
        ans: ""
    });

and onSubmit should be as below

function onSubmit() {
        // Calculate resultData based on inputData
        setResultData({
             name1: inputData.name1,
             name2: inputData.name2,
             result: 50

        });

        setResultVisibility(true);
    }

Upvotes: 2

Related Questions