How to force the state update to take place in React after calling setState?
As far as I know, state is effectively updated when render is called next time. Also, forceUpdate()
should re-render the component and update the state changes immediately, right? However this doesn't seem to be the case. Here's an example.
handleSomeEvent(data) {
this.setState({
data: data
})
this.forceUpdate()
// At this point state should be updated but it isn't
this.props.consumeData(this.state.data) // consumeData will receive old data
}
How do I ensure state is actually updated before calling consumeData?
How to force the state update to take place in React after calling setState?
As far as I know, state is effectively updated when render is called next time. Also, forceUpdate()
should re-render the component and update the state changes immediately, right? However this doesn't seem to be the case. Here's an example.
handleSomeEvent(data) {
this.setState({
data: data
})
this.forceUpdate()
// At this point state should be updated but it isn't
this.props.consumeData(this.state.data) // consumeData will receive old data
}
How do I ensure state is actually updated before calling consumeData?
Share Improve this question asked Jul 7, 2016 at 12:43 Tuomas ToivonenTuomas Toivonen 23.5k51 gold badges144 silver badges243 bronze badges2 Answers
Reset to default 15setState()
is asynchronous, so you can do it in the callback:
handleSomeEvent(data) {
this.setState({
data: data
}, () => this.props.consumeData(this.state.data)); // using `data` would work as well...
}
Regarding access to the state that just changed, @Samuli Hakoniemi's answer is the preferred way in the docs (iirc).
I'd say the following code should also run the state change before the data handling:
handleSomeEvent(data) {
const _handleDataChange = async () => {
this.props.consumeData(this.state.data)
}
this.setState({data: data})
_handleDataChange();
}
As _handleDataChange is an async call, it should be run after the (async) setState call.