How to respond to state changes in redux and send another action?

Can someone give me a hint on how to do the following with a reduct reduction:

Component A dispatches an action that updates state (async)

Component B (and not child component A) should be able to detect when the state changes and another action is sent.

My problem is that when I try to send action 2 to component B, the state is still in its original state and not being updated.

I also tried to perform dispatch action 2 in the WillUpdate component, but this creates an endless loop because the second action also updates the state (as well as asynchronously)

Here's what it looks, more or less:

//----- Component A class ComponentA extends React.Component { constructor(props) { super(props); this.props.dispatch(loadEvents()); // loadEvents is async and will update state.eventsState } } const mapStateToProps = function (state) { return { eventsState: state.eventsState, }; }; export default connect(mapStateToProps)(ComponentA); //----- Component B class ComponentA extends React.Component { constructor(props) { super(props); props.dispatch(getEventUsers(props.eventsState.eventId)); // the eventsState is in initial state here (empty)...where do I call getEventUsers? } componentWillUpdate(nextProps) { nextProps.dispatch(getEventUsers(props.eventsState.eventId)) // Creates an infinite loop, getEventUsers also updates state } } const mapStateToProps = function (state) { return { eventsState: state.eventsState, }; }; export default connect(mapStateToProps)(ComponentA); 
+7
reactjs redux react-redux
source share
1 answer

Without looking at your Redux code, I would say that your component B receives empty data in the constructor because it was creating component A at about the same time, and at that moment the async request initiated by the Component A constructor is still in process .

Your Redux should trigger an action containing the received data when the async request is complete. Then your gearbox puts this data into a state, which, in turn, changes the details of your connected components and forces them to restart.

You should only send getEventUsers if props.eventState.eventId exists and has changed.

+2
source share

All Articles