RetroMime
RetroMime

Reputation: 387

ReactJs - Child not updating after Parent State changed

Im new in ReactJS and I'm having problem with the concept of state and re-render of component.

In my parent component, I have this state in constructor:

this.state = {
        locale : 'en',
        messages : ENGLISH.messages,
        softwareInfo : {
                        software_name : 'Test Default 1.0',
                        default_dash : 1,
                        color_theme: '#009900'
                       }
    }

In the Render, I load a component called DashAppBar passing the softwareInfo:

<DashAppBar softwareInfo = { this.state.softwareInfo} />

In DashAppBar construct, I read that state as property:

this.state = {
       software_settings: props.softwareInfo,
       [...]
}

And then I print the software name in the bar with this:

const software_name = ( 
            <FormattedMessage 
                id="software_name" 
                defaultMessage="{software_name}"
                values={{software_name:this.state.software_settings.software_name}}
            />
        );

This work fine.

Unfortunally, parent component make an AJAX call that change softwareInfo:

success: function(result){
        //window.software_settings = $.parseJSON(result);
        //window.software_settings = result;
        var settings = {
                          software_name:result.software_name,
                          default_dash:result.default_dash,
                          color_theme:result.color_theme
                       };
        this.setState({softwareInfo : settings});
}

Calling setState should re-render the component but the child value remain the same as original and the new value got from AjaxCall are not displayed.

Where is the error? Change the parent state should update the child.

Thanks!

Upvotes: 3

Views: 7405

Answers (2)

Daniel Andrei
Daniel Andrei

Reputation: 2684

The issue is that you're passing the parent's state only in the child's constructor. If the parent updates props you either need to do componentWillReceiveProps and update the child state or just use the software_settings as prop directly.

For example, in the child component:

const software_name = ( 
            <FormattedMessage 
                id="software_name" 
                defaultMessage="{software_name}"
                values={{software_name:this.props.software_settings.software_name}}
            />
        );

or with componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    this.setState({ software_settings: nextProps.software_settings});
}

Upvotes: 4

Femi Oni
Femi Oni

Reputation: 814

you need to set a componentWillReceiveProps hook on your child component to updated it. https://reactjs.org/docs/react-component.html#componentwillreceiveprops

Upvotes: 0

Related Questions