0

I'm new to React and I'm trying to add objects one by one to an array in state when I submit a form but I only get one object in the array, here's a code snippet for that:

MY STATE

state = {
    comments: [],
    text: ""
  };

HANDLE FORM SUBMIT

 handleSubmit = event => {
    event.preventDefault();
    const arr = [];
    arr.push({ name: this.state.text, id: Math.random() });
    this.setState({ comments: arr, text: "" });
  };

RENDER METHOD

<form onSubmit={this.handleSubmit}>
          <input
            type="text"
            value={this.state.text}
            onChange={e => this.setState({ text: e.target.value })}
          />
          <ul>{this.renderComments()}</ul>
        </form>

3 Answers 3

1

Thats because every time you run handleSubmit function you create new empty array, push one new comment onto it and then replace whole comments field in state with it. To make it work just read from state what currently is held in comments array and push onto it instead of creating new one.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with you, this line const arr = []; needs to be updated to be const arr = this.state.arr
0

That's because every time handleSubmit is called the arr is initialized to an empty array,Remove the arr array and on submit spread the comments array and add the item

 handleSubmit = event => {
  event.preventDefault();
  this.setState({
   comments: [...this.state.comments,
   { name:this.state.text, id: Math.random() }
   ],text: ""});
 };

CodeSandbox here

Comments

0

To avoid to replace values in everytime, handle submit:

handleSubmit = event => {
    event.preventDefault();

    arr.push({ name: this.state.text, id: Math.random() });
    this.setState({ ...state, comment: [...state.comments, { name: this.state.text, id: Math.random() }] });
  };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.