I'm practicing react, and just now I'm about to make a to-do list. While i was working. I wanted to test my code with console.log to see input values are passing correctly to state. However for awhile I was confused to see how console.log would always output the previous state. Until later, i just embeded <p>{this.state.myArray}</p> and it shows it is working correctly. I presume this.setState({ myArray: this.state.message }); is still finishing executing while console.log already executed.
I'm pretty sure im using console.log the wrong way to test code. New programmer here.
class ToDoInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = { message: "", myArray: "" };
}
handleChange(e) {
this.setState({ message: e.target.value });
console.log("handleChange: " + this.state.message); //testing
}
handleSubmit(e) {
this.setState({ myArray: this.state.message });
console.log("handleSubmit: " + this.state.myArray); //testing
}
render() {
return (
<form>
<input
type="text"
value={this.state.content}
onChange={this.handleChange}
/>
<input type="button" value="submit" onClick={this.handleSubmit} />
<p>{this.state.myArray}</p>
</form>
);
}
}
this.setState, the console log in therethis.setState({message: e.target.value}, () => {console.log(this.state.message);});