2

Consider the following structure:

this.state = {
  States: [{
    Abbreviation: "MA",
    Cities: [{
      ID: 1,
      Name: "Boston",
      PropertyToUpdate: null
    },
    {
      ID: 2,
      Name: "Springfield",
      PropertyToUpdate: null
    }]
  }]
}

Given a city ID and a value, I need to update the PropertyToUpdate property to the value. So I would have a function that looks like:

handleUpdateProperty(cityID, newValue){
  // Do some things
  this.setState({...});
}

I have done some reading on immutable helpers but I'm not sure how to handle the two layers of nesting. I think it should look something like:

var newState = React.addons.update(
  this.state.States[indexOfState].Cities[indexOfCity],
  {PropertyToUpdate: {$set: newValue}}
);

...but this is not quite the right syntax. So how can I keep my state immutable, but still update this nested property of an array item?

1 Answer 1

9

You would use it like this

var newState = React.addons.update(this.state, {
  States: {
    [indexOfState]: {
      Cities: {
        [indexOfCity]: {
          PropertyToUpdate: {
            $set: newValue
          }
        }
      }
    }
  }
})

See nested collections.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.