monkeyjs monkeyjs - 13 days ago 5
React JSX Question

calling action creators on state/props change

Parent Component:

{this.state.Child2 ? (
<Child2 Colorvalue={this.state.activeColor} somename={this.state.name} />
) : (
<Child1 somename={this.state.name} Colorvalue={this.state.activeColor} />
)}


both in child1 & child2 components i have added a call to actioncreator (api call) to get some info - in ComponentWillMount method - everything works fine..

this.props.fetchData(somename, Colorvalue);


Now I need to update both children if Colorvalue changes on parent..I should call actioncreator with the new
'Colorvalue'

Should I have another call in update/receive props method of both the child components? How to handle this case.?

In each Child component there will be 2 calls to actionCreators if I do so?

Answer

You can dipatch the API call this.props.fetchData(...) in the parent. Then update this.state.activeColor in parent. Now pass that value as props to Child1 or Child2.

Inside your child components, since you're dispatching the action in ComponentWillMount, there won't happen a new API call in them when you supply new props from parent.

If you want to update internal states (if any) of the child components upon receiving the new props, you may use componentWillReceiveProps(nextProps).


UPDATE:

Child1 and Child2 receives new color from parent via props. So if you want to trigger the API call on receiving new props, dispatch this.props.fetchData(...) inside componentWillReceiveProps of child components.

hope you are using ES6 classes:

componentWillReceiveProps(nextProps) {
    if (this.props.Colorvalue !== nextProps.Colorvalue) {
        this.props.fetchData(this.props.somename, nextProps.Colorvalue);
    }
}

also I am assuming you have mapped the action creator fetchData as props to your child components using connect.

Comments