I am fairly new to React.js and just ran into a problem when trying to validate a form. I have the following form field and onChange function:
<AvField type="text" name="name" id="name" placeholder="Name" value={scheduleEvent.name} onChange={this.inputChange} className="form-control-sm" required />
inputChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
let scheduleEvent = {...this.state.scheduleEvent};
console.log(scheduleEvent);
scheduleEvent[name] = value;
console.log(scheduleEvent);
this.setState({scheduleEvent});
console.log(this.state.scheduleEvent);
}
When I type in "a", I get the following console.log outputs:
name a //as expected
{name: ""} //as expected
{name: "a"} //as expected
{name: ""} //this.state.scheduleEvent did not get updated
Then, if I type in another character, console.log outputs are as follows:
name aa //as expected
{name: "a"} //as expected, but for whatever reason it did not get updated on the first invocation of inputChange
{name: "aa"} //as expected
{name: "a"} // did not get updated
When I submit the form, however, this.state.scheduleEvent is correct.
I also tried this example linked from the React website: https://codepen.io/gaearon/pen/VmmPgp?editors=0010 The same issue exists there as well. Is there anyway to fix this?
Thanks