I have two handler functions for an onClick event on a button. Basically they do the same thing but one is incrementing an element (passed as a parameter) in the state array while the other is decrementing (but not the same variable). Say I have an array of two elements. I want the first element to be incremented and the second element to be decremented (array[0]++ array[1]--
).
HandleIncrement = instrumentUp => {
// create a shallow copy of the array
const tempCount = [...this.state.instrumentCount];
// increment the desired instrument
tempCount[instrumentUp] += 1;
// update the state
this.setState({
instrumentCount: tempCount
});
};
HandleDecrement = instrumentDown => {
// create a shallow copy of the array
const tempCount = [...this.state.instrumentCount];
// decrement the desired instrument
tempCount[instrumentDown] -= 1;
// update the state
this.setState({
instrumentCount: tempCount
});
};
I also have a button where these two methods are executed.
onClick = {() => {
this.HandleIncrement(0);
this.HandleDecrmenet(1);
}
}
The output is not desired. If this was the array = [0 1]
, I wish the output to be [1 0]
however the
the output is [0 0]
. I think this is because of these two functions being executed at the same time and so when they setState
, HandleDecrement
didn't use the updated state.
Should I be using something like async
or await
?