Hussian Shaik
Hussian Shaik

Reputation: 2693

how to setState to key inside a record in react

hai i am getting trouble when i try like this, i want to setState to key inside a record Example:

constructor(props){
    super(props);
    this.state = {
      data:{"firstName":"XXXXX",lastName:"YYYYY",Rank:1}
    }
}

i declare this in initial state,here i want to change only particular key like rank,for that i wrote like this:

this.Setstate({data.Rank:2})

it gives an Error any one give me suggestions how to resolve it, any help much appreciated

Upvotes: 1

Views: 1981

Answers (2)

user5703308
user5703308

Reputation:

You are setting state not correct.

If you have a component:

React.createClass({
  getInitialState: function(){
    return {
      data: {"firstName":"XXXXX",lastName:"YYYYY",Rank:1}
    };
  }
});

You need to do:

var data = this.state.data;
data.Rank = 2;

this.setState({
  data: data
});

Upvotes: 1

Naisheel Verdhan
Naisheel Verdhan

Reputation: 5133

Please go through this answer https://stackoverflow.com/a/34384198/3563619

You have to extend this.state to a newState, make changes in newState and and then setState(newState)

newState = Object.assign({}, this.state);    // clone this.state in a new object newState
newState.data.Rank = 2;                      // make changes to newState
this.setState(newState);                     // setState()

You can make any type and any number of modifications to newState and then use setState() without having any doubt over what you are doing.

Upvotes: 2

Related Questions