Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS setState with multiple nested arrays

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?

like image 782
Sean Avatar asked Dec 19 '25 04:12

Sean


1 Answers

You would use it like this

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

See nested collections.

like image 102
Rodrigo Siqueira Avatar answered Dec 20 '25 20:12

Rodrigo Siqueira