Manage State Locally First _Alternative Solution?

Manage State Locally First _Alternative Solution?
0

#1

Tell us what’s happening:
Hey guys, I think my code should be working well but I cannot pass the test. Any Ideas?

Your code so far


class DisplayMessages extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      messages: []
    };
    this.handleChange = this.handleChange.bind(this);
    this.submitMessage = this.submitMessage.bind(this);
  }
  // add handleChange() and submitMessage() methods here
  handleChange(e) {
    this.setState({
      input: e.target.value,
      messages: this.state.messages
    });
  }
  submitMessage() {
    this.state.messages.push(this.state.input);
    this.setState({
      input: '',
      messages: this.state.messages
    });
  }
  render() {
    const items = this.state.messages.map(
      message => <li key={message}>{message}</li>
    );
    return (
      <div>
        <h2>Type in a new Message:</h2>
        { /* render an input, button, and ul here */ }
        <input onChange={this.handleChange} value={this.state.input} />
        <button onClick={this.submitMessage}>Add message</button>
        <ul>
          {items}
        </ul>
        { /* change code above this line */ }
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react-and-redux/manage-state-locally-first


#2

You should never mutate state directly. Only use setState.


#3

The problem is solved. Thanks.