1

I am trying to update form through useState React Hook

const [loginForm, setLoginForm] = useState({
    username: {
        value: "",
        validation: {
            required: true
        },
        valid: false,
        touched: false,
    },
    password: {
        value: "",
        validation: {
            required: true
        },
        valid: false,
        touched: false,
    }

})

My input element is using onChange Event which calls a function. Here key is either username or password according to the for loop

<input className={classes.input_element} type="text" name="{key}" value={loginForm[key].value} onChange={event => inputChangedHandler(event, key)} required />

inputChangedHandler definition is as follows:

const inputChangedHandler = (event, inputIdentifier) => {
    event.preventDefault();
    const updatedField = updateObject(loginForm[inputIdentifier], {value: event.target.value, touched: true, )})
    const updatedForm = updateObject(loginForm, {[inputIdentifier]: updatedField,})
    setLoginForm(updatedForm)
    console.log(updatedForm)
    console.log(loginForm)
}

In the above code, in the last 3rd line, I am setting the actual value of loginForm with the updatedForm. But when I am logging the updatedForm and loginForm to the console, both are giving different outputs.

updatedForm

{username: {…}, password: {…}}
password: {value: "", validation: {…}, valid: false, touched: false}
username: {value: "a", validation: {…}, valid: true, touched: true}
__proto__: Object

loginForm

{username: {…}, password: {…}}
password: {value: "", validation: {…}, valid: false, touched: false}
username: {value: "", validation: {…}, valid: false, touched: false}
__proto__: Object

In the input field, I am picking the value from the loginForm only and there I am getting the actual updated value. Why is this happening?

1 Answers1

2

You need a useEffect with dependency updatedForm

useEffect(()=> {
    //do what every you want when  updatedForm changes
},[updatedForm])
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54