I am checking the state of one of my keys twice within a function. However, even after operations are done on the key value it still reports the same value.
So I have a function called clickMe
that will run from an onClick
event for a button I have in the return for the component. When it's clicked the function should check to see the current state of totalRemaining before performing operations. If totalRemaining is greater than 0 it should uptick clicks and downtick totalRemaining. After that operation it should check to see if totalRemaining is still greater than 0. If it isn't it should disable the button. However, before and after the operation the value of totalRemaining is the same even though after render it is clear that it has been updated.
import React from 'react';
class Item extends React.Component{
constructor(props){
super(props);
this.state = {
clicks: 0,
totalRemaining: 10,
disabled: false,
}
}
clickMe(){
if(this.state.totalRemaining>0){
console.log(`Clicks: ${this.state.clicks}`)
console.log(`Total Remaining: ${this.state.totalRemaining}`)
this.setState({
clicks: this.state.clicks + 1,
totalRemaining: this.state.totalRemaining - 1
});
console.log(`Clicks: ${this.state.clicks}`)
console.log(`Total Remaining: ${this.state.totalRemaining}`)
if(this.state.totalRemaining===1){
this.setState({
disabled: true
})
}
}else{
this.setState({
disabled: true
})
}
}
render() {
return(
<div>
<button onClick={() => this.clickMe()} disabled={this.state.disabled}>Click Me {this.props.name}</button>
<input placeholder={this.state.totalRemaining}/>
<input placeholder={this.state.clicks}/>
</div>
)
}
}
export default Item;
Here is the console output:
this.state.totalRemaining
10
MyItem.js:18 Clicks: 0
MyItem.js:19 Total Remaining: 10
this.state.totalRemaining
10
this.state.totalRemaining
10
MyItem.js:25 Clicks: 0
MyItem.js:26 Total Remaining: 10