state = {
a: 1,
b: 2,
};
updateState = () => {
const { a, b } = this.state;
console.log("previous a", a);
console.log("previous b", b);
this.setState({ a: b, b: 3 });
console.log("New a", a); <-- getting previous value here
console.log("New b", b); <-- getting previous value here
};
is it possible to get a new value in the same function?
No. But setState has a second parameter where you can supply a function that gets called after the state has been updated (and the component has been re-rendered). However usually it’s better to use componentDidUpdate() instead.
can you show me how componentDidUpdate() applies here?
componentDidUpdate(prevProps, prevState) {
if (this.state.b != prevState.b) {
console.log("previous b", prevState.b);
console.log("new b", this.state.b);
}
}