I just finished working with this exercise, but I’m in the midst of playing around with it, and I came across a question. With the following code, when I console.log(this.state) in my submitMessage() function, it console.logs the previous state? Why is the function operating in that way?
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
}
// add handleChange() and submitMessage() methods here
// this.handleChange = this.handleChange.bind(this)
// this.submitMessage = this.submitMessage.bind(this)
handleChange(event) {
this.setState({
input: event.target.value,
messages: this.state.messages
})
}
submitMessage() {
this.setState({
input: '',
messages: [...this.state.messages, this.state.input]
});
console.log(this.state)
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input onChange={this.handleChange.bind(this)} value={this.state.input}/>
<button onClick={this.submitMessage.bind(this)}>Submit</button>
<ul>
{this.state.messages.map((x,i) =>{return <li key ={i}>{x}</li>})}
</ul>
{ /* change code above this line */ }
</div>
);
}
};