I have the following state in my React Component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
temperatureBedroom: 22.0,
temperatureLivingRoom: 23.0,
...
Now, I would like to update the state with the this.setState
function.
The most straightforward way to do it is to just use the following code:
increaseTemp = () => {
let increment = 0.5;
this.setState({
temperatureBedroom: this.state.temperatureBedroom + increment
});
...
However, the problem is that with this approach I have to define a new (handler) function for each of the states (variables), i.e., as in my example -- rooms, for which I'd like to set a new value (temperature).
I was wondering if there is a more efficient way in React to address this issue.
The desired outcome would be to have something like that for the Buttons control:
<Button
variant="outline-secondary"
onClick={() =>
this.increaseTemp("temperatureBedroom")
}
>
+
</Button>
and I would like to use this argument like that:
increaseTemp = (roomName) => {
let increment = 0.5;
this.setState({
roomName: this.state.roomName + increment
});
...
The documentation doesn't mention a simple way to do it. It shows an example of writing separate handler functions for each state variable, see e.g.: https://beta.reactjs.org/learn/updating-objects-in-state
I have found similar questions, but some other aspects of the setState
are discussed there, none of them addresses specifically the issue I would like to resolve:
Maybe I could try using a function as a setState
parameter, but I am not sure if it helps with my problem: https://medium.com/@wisecobbler/using-a-function-in-setstate-instead-of-an-object-1f5cfd6e55d1
I would appreciated any suggestions how to avoid writing redundant handler functions.