How can we access updated states in the same function?
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?
async and await are not working here. function method where we apply function as a 2nd parameter to the setstate is not working for the whole application.
please do not flag this question.
You could use this.setState's callback in this way:
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", this.state.a);
console.log("New b", this.state.b);
});
};
EDIT to print new state values you could use also componentDidUpdate in this way:
componentDidUpdate(prevProps, prevState) {
if (prevState.a !== this.state.a) {
console.log("New a", this.state.a);
}
if (prevState.b !== this.state.b) {
console.log("New b", this.state.b);
}
}
you are using a local constant variable whose value is not changed. so if you want to use updated value use this.state.a and this.state.b for respective value.
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 // problem is here
console.log("New b", b); <-- getting previous value here // problem is here
//replace above code with below code
console.log("New a", this.state.a); //replace with this code.
console.log("New b", this.state.b); //replace with this code
};