Redux connect() with multiples actions / states

Livioso picture Livioso · Feb 17, 2016 · Viewed 12.7k times · Source

What is the proper way of connecting multiple states with corresponding action creators in Redux? And is that even a good idea? How can I work around that if it's a stupid idea?

export default connect(

// which part of the Redux global state does
// our component want to receive as props?
(state) => {
  return {
    state: state.instagram
  };
},

// which action creators does
// it want to receive by props?
(dispatch) => {
  return {
    actions: bindActionCreators(instagramActions, dispatch)
  };
}

)(FeedContainer);

What I basically want is something like this:

...
state: {state.instagram, state.facebook}
...

...
const mergedActions = {instagramActions, facebookActions};
actions: bindActionCreators(mergedActions , dispatch)
...

Answer

larrydahooster picture larrydahooster · Feb 17, 2016

Using the provided callbacks mapStateTopProps and mapDispatchToProps is the proper way to connect your component with a filtered subset of your state and already bound actionCreators.

To achieve what you want you could simply do:

(state) => {
  const { instagram, facebook } = state;
  return {
    state: { instagram, facebook }
  };
}

and

(dispatch) => {
  return {
     actions: bindActionCreators(Object.assign({}, instagramActions, facebookActions), dispatch)
  };
}

This does not work:

actions: bindActionCreators({instagramActions, facebookActions} , dispatch)

as the method does not support nested objects yet. See code here. It only iterates over the keys and looks for functions.

Within your mapDispatchToProps callback you could leave the extra state layer away

(state) => {
   const { instagram, facebook } = state;
   return {
      instagram, 
      facebook
   };
}

By doing this you can access the props with:

this.props.facebook and this.props.instagram instead of this.props.state.facebook and this.props.state.instagram. But this is only a question of style I think.

There are several ways of binding your state and dispatch to props. In the end it is a question of style. I could provide several different examples of how to do it, but better take a look into the official documentation and find your own style https://github.com/reactjs/react-redux/blob/master/docs/api.md