Jan Swart
Jan Swart

Reputation: 7221

Reuse mapStateToProps by composing connect functions

I have situation where, for example, three components use the same state from the store, as well as state unique to them.

I would like to refactor this, so I don't duplicate the work, by doing something like this:

const sharedMapStateToProps = state => ({
  sharedValue1: state.sharedValue1,
  sharedValue2: state.sharedValue2,
  sharedValue3: state.sharedValue3,
});

const uniqeMapStateToProps = state => ({
  uniqueValue1: state.uniqueValue1,
  uniqueValue2: state.uniqueValue2,
});

compose(
  connect(sharedMapStateToProps),
  connect(uniqeMapStateToProps)
)(SomeComponent)

Are there ways to reuse and combine mapStateToProps / mapDispatchToProps / mergeProps functions?

Upvotes: 0

Views: 205

Answers (1)

Safi Nettah
Safi Nettah

Reputation: 1170

Have you tried this ?

compose(
  connect(state => ({ ...sharedMapStateToProps(state), ...uniqeMapStateToProps(state) })),
)(SomeComponent)

Upvotes: 1

Related Questions