Can someone give me clues on how to do the following with react-redux:
Component A dispatches an action that updates the state (async)
Component B (not a child component of A) needs to be able to detect when the state changes and dispatch another action.
My problem is when I try do dispatch action 2 in component B, the state is still in the initial state and it is not updated.
I also have tried dispatching action 2 in componentWillUpdate, however, that creates an infinite loop because the second action also updates the state (and also asynchronously)
This is how it looks like, 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);
Without looking at your Redux code, I'd say your Component B is getting empty data in the constructor because it's instantiated at about the same time a Component A, and at that point the async request initiated by Component A constructor is still in progress.
Your Redux should fire an action that contains the received data when the async request completes. Your reducer then puts this data in the state, which in turn changes the props of your connected components and forces them to rerender.
You should dispatch getEventUsers only when props.eventState.eventId exists and has changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With