0

I wonder what is the best approach to dry out common redux actions ('m using redux-thunk)

for example I have these two components:

const Main = ({list, onLike }) => (
  <ul>
    {list.map(item => (
      <Comment item={item} onLike={onLike} />
    ))}
  </ul>
)

const mapStateToProps = (state) => ({
  list: state.main.comments
})

const mapStateToProps = (dispatch) => ({
  onLike: (commentId) => dispatch(actions.mainOnLike(commentId))
})

export default connect(mapStateToProps, mapDispachToProps)(Main)
const Profile = ({ list, onLike }) => (
  <ul>
    {list.map(item => (
      <Comment item={item} onLike={onLike} />
    ))}
  </ul>
)

const mapStateToProps = (state) => ({
  list: state.profile.comments
})

const mapStateToProps = (dispatch) => ({
  onLike: (commentId) => dispatch(actions.profileOnLike(commentId))
})

export default connect(mapStateToProps, mapDispachToProps)(Profile)

actions.js

  export const mainOnLike = commentId => dispatch => {
    commentsService.like(commentId).then(() => {
      dispatch(mainReloadComments())
    })
  }

  export const profileOnLike = commentId => dispatch => {
    commentsService.like(commentId).then(() => {
      dispatch(profileReloadComments())
    })
  }

This is an example to show the problem. The point is that I'm calling commentsService.like multiple times and I will like to dry that out. The reason for that is that I need to call profileReloadComments and mainReloadComments separated to reload the comments in store for those containers/reducers.

I'm tempted to call commentsService.like inside the <Comment> component, so whenever I use it I have that functionality, but that does not seems the redux way.

any ideas how to dry this out? Thanks!

Federico
  • 5,438
  • 5
  • 39
  • 47

1 Answers1

2

Probably something like this:

const likeCommentWithAction = actionCreator => commentId => dispatch => {
  commentsService.like(commentId).then(() => {
    dispatch(actionCreator())
  })
}

// Then
export const mainOnLike = likeCommentWithAction(mainReloadComments)
export const profileOnLike = likeCommentWithAction(profileReloadComments)

Chad S.
  • 6,252
  • 15
  • 25