Issue:
I am unable to change the state duynamically. I need to change the state object's key as per the input field's "name" attribute.
Code:
const addressValue = (e) => {
setAddress(state => ({
...state,
[e.target.name]: e.target.value
}));
};
/****************************************************************
* giving error while typing "Cannot read property 'name' of null"
*****************************************************************/
<form onSubmit={submitHandler}>
<div className="form-group">
<input id="address-line-1" className="form-control" value={address.line1}
onChange={addressValue} name="line1" type="text" placeholder="Line 1" />
</div>
<div className="form-group">
<input id="address-line-2" className="form-control" value={address.line2}
onChange={addressValue} name="line2" type="text" placeholder="Line 2" />
</div>
</form>
Object's initial value
{
line1 : "CA",
line2 : "US"
}
eventhas been reset before it gets used. Solution would be to usee.persist()or save the relevant values to other variables outside the event object. Or another option would be to not use a functional update, since your new state is not derived from the previous state.