Reputation: 8889
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
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.
Upvotes: 3
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
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)
}
Upvotes: 0