1

`Trying to update array of objects in onClick. I'm having two states namely "intialValue" and "todos" in array format. When I check in the react developer tool I can see there are two states. The task's flow is user can enter the text in input textbox, once the user click's the add button I want that to be add as a array of objects, I've kept one Boolean field and Id field. The problem I'm facing is I can get the "inputvalue" correctly. I'm also getting the array of objects but not in "todos" state, and the values are not getting updated in array format only the input value is getting changed. For Example : 0{completed:false, id:20, text:abc} when I'm clicking add button the array is not getting updated as 1{completed:false, id:20, text:cde} , instead in the 0th postiton itself values are getting updated. I've added the code below Could any one help me to achieve the output. Thanks in advance.

` enter image description here

class TodoForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      InputValue: "",
      todos: [],
    };
    console.log("intialvalue", this.state.InputValue);
  }

  handleChange(e) {
    this.setState({ InputValue: e.target.value });
  }

  handleSubmit(e) {
    //   alert("Form state value" + this.state.initalValue);
    e.preventDefault();
    this.setState([
      ...this.state.todos,
      {
        text: this.state.InputValue,
        completed: false,
        id: Math.random() * 1000,
      },
    ]);
  }
  render() {
    return (
      <div className="Todo">
        <form>
          <input
            type="text"
            value={this.state.InputValue}
            onChange={this.handleChange.bind(this)}
          ></input>
          <button onClick={this.handleSubmit.bind(this)}>Add</button>
        </form>
        <p>{this.state.InputValue}</p>
      </div>
    );
  }
}

export default TodoForm;
Still_Learning
  • 209
  • 3
  • 14

1 Answers1

3

You hava to update todo state(not entirely state). You are not updating state correctly. It should be like this:

this.setState({
      todos: [
        ...this.state.todos,
        {
          text: this.state.InputValue,
          completed: false,
          id: Math.random() * 1000
        }
      ]
    });

Here is the demo: https://codesandbox.io/s/gracious-mountain-rdubi?file=/src/App.js

Shubham Verma
  • 4,918
  • 1
  • 9
  • 22