2

If I have something like the following:

export default class Questions extends Component {

  state = {
    questions: [
      {value: 'value one, required: true},
      {value: 'value two, required: true},
      {value: 'value two, required: true} 
    ]
  };
...

...and I want to change the middle object's required to false, what would be the best way? So I would end up with:

questions: [
  {value: 'value one, required: true},
  {value: 'value two, required: false},
  {value: 'value two, required: true} 
]

I tried:

_toggleRequired = (index) => {
  this.setState({
    questions[index].required = !questions[index].required
  })
}; 

... but it's giving me a syntax error on the first [index]. Isn't it also probably best to return a new array instead of mutating the existing one?

TIA!

13
  • What you have is simple not a valid objet literal. Have you ever seen foo({bar = baz}) anywhere? Commented Apr 5, 2016 at 17:05
  • There is also this for redux: stackoverflow.com/q/35592078/218196 . Commented Apr 5, 2016 at 17:07
  • It's not a exact duplicate, I have an array of objects,,, the duplicate reference is an object - not an array. I am also not clear on the point you are trying to make - if there is one. Marking it as an exact duplicate when it is not does not help or even come close to an answer. Commented Apr 5, 2016 at 17:17
  • Did you even read the accepted answer? Did you try to apply it to your use case? Did you have a look at facebook.github.io/react/docs/update.html, as the answer recommends, and read about the methods specifically available for arrays? (FWIW, an array is also an object) Commented Apr 5, 2016 at 17:21
  • 2
    If you need a concrete example of how to apply the suggestion in the accepted answer to an array, here it is: var newQuestions = update(this.state.questions, {[index]: {required: { $set: !questions[index].required } });. All I changed was the property names and targeted the right array element. Commented Apr 5, 2016 at 17:43

1 Answer 1

2

If you don't want to deal with immutable objects than this is what I recommend. If you create a new array of objects from the current state, make your changes to the object at the particular index, and then save that object as the state it should accomplish what you're trying to do.

_toggleRequired = (index) => {
  let q = this.state.questions;
  q[index].required = !q[index].required
  this.setState({questions : q });
}; 
Sign up to request clarification or add additional context in comments.

1 Comment

React doesn't really allow you to setState on an attribute of an object.? Are you kidding. It allows.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.