React: Update state variables shorthand

In React, to handle variable changes, we do:

handleChangeRound = (round) => {
  this.setState({round: round});
}

updateLoading = (isLoading) => {
  this.setState({isLoading: isLoading});
}

Is there a way to write

this.setState({round: round});
this.setState({isLoading: isLoading});

as

this.updateState(round);
this.updateState(isLoading);

given the variables round and isLoading exist in the state and correspond to the variable name to avoid the redundant variable: variable?


PS: Inspired by:

console.log({x: x, y: y});
// output:
// {x: 10, y:20}

can be written as

console.log({x,y});
// output:
// {x: 10, y:20}

Upvotes: 2

Views: 206

Answers (3)

Murat Karagöz
Murat Karagöz

Reputation: 37594

You can write it as

this.setState({round});
this.setState({isLoading}); 

by using the Object Property Shorthand from ECMAScript 6 / ES2015. Basically the idea behind this is that you can omit the property key since the variable declaration has the key.

Property definitions

Upvotes: 3

Mohamed Assem
Mohamed Assem

Reputation: 164

you can use setState with call back

this.setState(prevState => {
 return {
   isLoading:!prevState.isLoading
 }
})

or you can do what ever from the prevState

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281676

All you need is to write setState with a dynamic obj and pass in an object to the function like

this.updateState({ round });
this.updateState({ isLoading });

updateState = (obj) => {
   this.setState(obj)
}

Sample Demo

Upvotes: 0

Related Questions