I have a few methods in my React component, all of which modify state:
class Abc extends React.Component {
state = {
f1 : 'f1',
f2 : 'f2',
f3 : 'f2',
dynamicValue : 'some initial value',
}
func1 = () => {
//..do some work
this.setState({ f1 : someValue1})
}
func2 = () => {
//..do some work
this.setState({ f2 : someValue2})
}
func3 = () => {
//..do some work
this.setState({ f3 : someValue3})
}
doWorkAfterAllSetStateIsComplete = () => {
const val = this.state.dynamicValue;
// I get stale state here
}
doWork = () => {
func1();
func2();
func3();
doWorkAfterAllSetStateIsComplete();
}
}
If I call doWorkAfterAllSetStateIsComplete
in a setTimeout
like this, I get the updated state.
setTimeout(() => {
doWorkAfterAllSetStateIsComplete();
// this.state.dynamicValue is updated here.
}, 0)
I know this is happening because setState
is async
and setTimeout
calls doWorkAfterAllSetStateIsComplete
in the next 'tick' of JavaScript, and so I get the updated state value inside doWorkAfterAllSetStateIsComplete
. But this seems a little hacky to me. Is there another way to achieve this?