I'm new to React and I want to update the state of an object when the input changes its value.
I've searched some references relating to this and there are several solutions, like this. However, it doesn't work correctly for me.
Applied this solution, I get the value incorrectly. For example, I type the input value: "name", but the value I get is only "nam". The last character is missing.
What's wrong here? Anyone here can help me? Thank you in advanced.
Here is my code for component AddHero.js
import React, { Component } from 'react';
class AddHero extends Component {
constructor(props) {
super(props);
this.state = {
hero: {}
};
this.addHero = this.addHero.bind(this);
this.nameChange = this.nameChange.bind(this);
}
addHero() {
}
nameChange(event) {
var temp = {...this.state.hero};
temp.Name = event.target.value;
this.setState({hero:temp});
console.log(this.state.hero.Name);//the value of Name is always missing the last character from the input
}
render() {
return (
<div>
<div className="name">
<label>Name: </label>
<input type="text" id="Name" onChange={this.nameChange} />
{/* <p class="alert alert-danger invalid" >Invalid Name</p> */}
</div>
<div className="submit">
<button type="button" onClick={this.addHero} >Add new</button>
</div>
</div>
);
}
}
export default AddHero;
Here is the snapshot: