Manage State Locally First Map not a Function

Tell us what’s happening:

// running test
this.state.messages.map is not a function
this.state.messages.map is not a function
// tests completed

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,
    });
  }

  submitMessage(e){
    this.setState({
      input: '',
      messages: this.state.messages.push(this.state.input)
    });
  }
  render() {
    const messages = this.state.messages.map(function(message){
      return <li> {message} </li>}
    );
    return (
      <div>
        <h2>Type in a new Message:</h2>
        <input
          type='text' 
          onChange={this.handleChange} 
          value={this.state.input} />
        <button onClick={this.submitMessage}> 
          Add Message
        </button>
        <ul>
          {messages}
        </ul>

      </div>
    );
  }
};

Your browser information:

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

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

Array.prototype.push does not return the array as you’re expecting, but the length of the array after pushing the element. You’ll have to refactor submitMessage.

Thanks, .concat did the trick. But i think is not the right way to do it, cuz .concat modifies the original array , so is redundant. Any Better way?

Regards.

It doesn’t, though. Array.prototype.concat returns a new array, which is how it works in your code. I wouldn’t worry about optimizing this any further, just move on to bigger problems.

Thanks for pointing out the return value using the Array.prototype.push method. I was having the same issue, but reading this resolved it for me. I refactored using the spread operator.