Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to respond to state change in redux and dispatch another action?

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);
like image 784
mvovchak Avatar asked Jun 29 '16 22:06

mvovchak


1 Answers

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.

like image 69
Miloš Rašić Avatar answered Nov 15 '22 04:11

Miloš Rašić