Home > OS >  setState does not change state in React in a functional component
setState does not change state in React in a functional component

Time:09-16

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>
    );
}

CodePudding user response:

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]);

CodePudding user response:

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);
    }
  • Related