Home > Software engineering >  Can't insert state values into an object
Can't insert state values into an object

Time:01-30

I have this state in my class:

this.state = {
  inputValue: "",
  todos: []
}

In an arrow function, I am trying to setState in order to put inputValue into todos.

this.setState({ inputValue: "", todos: [...this.state.todos, {this.state.todos.length: this.state.inputValue}] })

However, when I try to insert the inputValue and the number, it gives an error. Any help is appreciated as I am new to React.

CodePudding user response:

If you want a resulting todos array like this:

[
  {0: "something"},
  {1: "Else"}
]

The square bracket notation is needed to use a variable as the object key.

this.setState({
    inputValue: "",
    todos: [
      ...this.state.todos,
      { [this.state.todos.length]: this.state.inputValue }
    ]
});
  •  Tags:  
  • Related