[help] Manage State Locally First

Hello, I’m not sure what I’m doing wrong with this one. :thinking:

hi @danilogeronimo

The convention to ask for help in the forum is posting a specific question, share your formatted code and add a link to the exercise.

Right now, it’s too hard to read it.

The exercise is this https://learn.freecodecamp.org/front-end-libraries/react-and-redux/manage-state-locally-first

I can’t pass the last test and I don’t understand why :frowning:
image

submitMessage(){  
    newArr.push(this.state.input);
    this.setState({
      messages:[...newArr],
      input: ""
    })   
  }  
 render() {
    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</button>
        <ul>          
          {this.state.messages.map(e=><li>{e}</li>)}       
        </ul>
        { /* change code above this line */ }
      </div>
    );
  }

and it looks functional :thinking:
image

What does your newArr look like?

Can you paste your full code instead of snippets?

Thanks for the reply!

image

sure

let newArr = [];
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 (event){  
    this.setState({
      input:event.target.value
    }) 
  }

  submitMessage(){  
    newArr.push(this.state.input);
    this.setState({
      messages:[...newArr],
      input: ""
    })   
  }  

  render() {
    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</button>
        <ul>          
          {this.state.messages.map(e=><li>{e}</li>)}       
        </ul>
        { /* change code above this line */ }
      </div>
    );
  }
};

Alright.

So just as I suspected newArr was the problem. First of all, I would safely declare your newArr variable inside submitMessage function. The instruction says,

The submitMessage() method should concatenate the current message (stored in input ) to the messages array in local state…

But you are currently only adding current inputs to newArr instead of concatenating existing values inside. So I would do simply add this line above your push method.

let newArr = [...this.state.messages];

1 Like