Reputation:
I´m working on a React project, which involves displaying a value (DisplayValue) and then storing that value inside state so that I can use it later. Problem is state is always one step behind (for instance, if displayValue is "12", value is just 1). I need both values to be the same. Is it because setState is async? How can I fix it?
inputDigit(digit) {
const {
pendingOperation,
displayValue
} = this.state;
if (pendingOperation) {
this.setState({
displayValue: String(digit),
pendingOperation: false
})
}
value1 = parseFloat(displayValue);
this.setState({
displayValue: displayValue === "0" ? String(digit) : displayValue + String(digit),
value: value1
}, () => {
console.log(this.state.value)
})
};
Codepen: https://codepen.io/HernanF/pen/jXzPJp
Upvotes: 0
Views: 321
Reputation: 1074198
You're breaking a fundamental React rule: Never set state based on existing state by passing an object into setState
. Instead, use the callback form, and use the state object the callback form receives. You also probably want to call setState
once, not (potentially) twice.
So, you want those changes in the update callback, something like this:
inputDigit(digit) {
this.setState(
({pendingOperation, displayValue}) => {
const newState = {};
if (pendingOperation) {
newState.displayValue = String(digit);
newState.pendingOperation = false;
}
newState.value = parseFloat(displayValue);
// Not sure what you're trying to do with the second setState calls' `displayValue: displayValue === "0" ? String(digit) : displayValue + String(digit),`...
return newState;
},
() => {
console.log(this.state.value)
}
);
}
Upvotes: 2
Reputation: 2970
There seem to be a problem in the code, not React
value1 = parseFloat(displayValue);
should be
value1 = parseFloat(displayValue + String(digit));
The same as for displayValue
Upvotes: 0