Joel
Joel

Reputation: 93

React-Native setState - both name and value from the same variable

Is it possible to enter only one argument to SetState that contains both the name and the value. See the example below. Is there something wrong with the brackets?

This would be handy when changing a lot of states at the same time. That is, first prepare them in one long string and execute setState only once. Thank you!

this.setState({myState: "help"}) // this works of course
whatstate='myState'
this.setState({[whatstate]: "me"}) // this too
whatstate2='myState: "please"' 
this.setState(whatstate2) // but how to make this work?

Upvotes: 2

Views: 1419

Answers (2)

Mr.J4mes
Mr.J4mes

Reputation: 9266

You can call this.setState({ whatstate2 }) to achieve the same effect. This is the property value shorthand from ES6.

Reference: https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand

In case you'd like to update multiple states in one go, you can also do that like this.

this.setState({
    myState1 : newState1,
    myState2 : newState2
});

If the variable names are the same as the state names as mentioned previously, you can do.

this.setState({ myState1, myState2 });

Upvotes: 1

wicky
wicky

Reputation: 978

// if you like to work only with strings
var whatstate = {};
whatstate['myState1'] = 'help';
whatstate['myState2'] = 'me';
whatstate['myState3'] = 'please';

// ^ this will produce an object equivalent to this
//whatstate = {
//  myState1: 'help',
//  myState2: 'me',
//  myState3: 'please'
//}

// which you can use it to 'setState'
this.setState(whatstate);

Upvotes: 2

Related Questions