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

109
Views
Spread Operator Dynamic Properties Update

I have a state that looks like this:

state: {
    1: {show: false, description: 'one'},
    2: {show: false, description: 'two'},
    3: {show: true, description: 'three'}
   }

Depending on a variable "id" that comes from the action, I have to update the state.

Something like this:

var returnedState = {...state, [id].show : ![id].show}

How can I do this?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

{...state,
 [id]: {
  show: !state[id].show 
 }
}

that will copy the original state and then toggle the show value for the specific key/id that came from the action.

Here is a working code pen http://codepen.io/finalfreq/pen/mRBjZV

over 4 years ago · Santiago Trujillo Report

0

The previous answer was correct but just leaves the show property on the sub object, removing the other ones. To keep all properties and change the property you want you have to use:

 {...state, [id] : {...state[id], show: !state[id].show}}

Have to add ...state[id]

over 4 years ago · Santiago Trujillo Report

0

this.setState(prevState => ({
...state,
state[id]: !prevState[id].show
}))

Here you have to take last state as prevState and then update the object with supplied key with opposite value of previous state's object.

over 4 years ago · Santiago Trujillo 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!