Simantov Yousoufov
Simantov Yousoufov

Reputation: 112

ReactJS: Child component updates before parent state is set

I have parent and child components where the state of the child (openWhen is essentially a shouldChildRender) is controlled by the parent. I'm running into an issue where the child is updated (receives props) before the parent state is updated after calling the parent's setState() so the child receives stale state until the second pass through of this flow. In the second pass through the child receives the updated state and renders correctly.

Parent:

openDeactivateWarning: function (resource) {
    this.setState({
        openDeactivateModal: true,
        workingResource: resource
    });

    console.log('this.state.openDeactivateModal is still false here', this.state);
},

render: function () {
    return (
        <Modal openWhen={this.state.openDeactivateModal} openCallback={this.openDeactivateWarning}>
            <p>Some Modal content</p>
        </Modal>
    )
}

Child:

componentWillReceiveProps: function () {
    console.log('This is fired before parent state changes and openModal is not called');

    if (this.props.openWhen) {
        this.openModal();
    }
},

I know that setState() does not immediately result in a state change but I was under the impression that children would still be re-rendered after state is actually changed. Is there a more preferable way of accomplishing this?

Upvotes: 4

Views: 738

Answers (1)

Phi Nguyen
Phi Nguyen

Reputation: 3056

you should use nextProps which is updated. this.props.openWhen in componentWillReceiveProps is still the old one when the parent component updates it's state.

componentWillReceiveProps: function (nextProps) {
    console.log('This is fired before parent state changes and openModal is not called');

    if (nextProps.openWhen) { <-- updated props
        this.openModal();
    }
}

Upvotes: 4

Related Questions