I have a main component which stores the state and has a function called handleBtnClick which manipulates the state value.
I have another component which calls the function handleBtnClick when a button is pressed. I have a displayComponent that I pass the state value to display in the form.
I know setState is asynchronous, so the displayComponent value is always one step behind. How can I fix this using the callback in setState or is there another way?
MainComponent
class SomeComponent extends React.Component {
constructor (props) {
super (props)
this.state = {value: 1}
}
handleBtnClick = (values) => {
const newValue = this.state.value * values;
this.setState({value: newValue});
}
render() {
return (
<div>
<ButtonComponent onClick={this.handleBtnClick} />
<DisplayComponent displayValue={this.state.value}/>
</div>
);
}
}
ButtonComponent
class ButtonComponent extends React.Component {
render() {
return (
<div>
<button onClick={() => this.props.onClick(123)}> // pretent this value always changes
Button
</button>
</div>
);
}
}
DisplayComponent
class DisplayComponent extends React.Component {
render() {
return (
<div>
{this.probs.displayValue}
</div>
);
}
}
EDIT:
Sandbox example here (thanks Shubham): https://codesandbox.io/s/5kx9yk7934
On the first button click the value displayed in label is 0, even though it should be 4. On second click it updates to 4.
How can I make sure on first click the value is always correct (i.e 4) by only using the state value for calculation.