Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Can't insert state values into an object

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 }
    ]
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!