0

I'm currently writing a React project (using redux and recompose) and are trying to pass my redux state to my dispatch inside my connect.

I'd like to avoid writing my connect code twice, but have had to do so in order to make the currentLocaleCode appear in state, so that the dispatch can grab it from my local state.

Here's how that looks:

export default compose(
  connect(
    (
      {
        locales: { currentLocaleCode }
      }
    ) => ({ currentLocaleCode })
  ),
  connect(null, (dispatch) => ({
    fetchPage: () =>
      dispatch(pagesActions.fetchPage(currentLocaleCode))
  })),
...

I would like to immediately have the currentLocaleCode available and achieve something like the following:

export default compose(
  connect(
    ({ locales: { currentLocaleCode } }) => ({ currentLocaleCode }),
      (dispatch, { currentLocaleCode }) => ({
        fetchPage: () =>
          dispatch(pagesActions.fetchPage(currentLocaleCode))
      }),
...

Is this possible?

dnlmzw
  • 751
  • 1
  • 8
  • 20

1 Answers1

0

Instead of using two connect HOCs you could simply pass the data on to the component as props and call the action creator with the required data

like

export default compose(
  connect(({locales: { currentLocaleCode }}) => ({ currentLocaleCode }),
  (dispatch) => ({
    fetchArticles: (dispatch) => ({
      fetchPage: =>
        (currentLocaleCode) => dispatch(pagesActions.fetchPage(currentLocaleCode))
    })
  })),
...

and in the connected component you would call the fetchPage like

this.props.fetchPage(this.props.currentLocaleCode);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Hi Shubham, I'd accidentally added some extra code which was not supposed to be there. I've removed it now. Basically `fetchArticles` and `fetchPage` were not supposed to be written into each other, and my question was rather how to avoid writing `connect` twice. – dnlmzw Mar 29 '19 at 10:39
  • In regards to your comment, I'd like to avoid having to pass the `currentLocaleCode` every time I call my method, as it is already available in my state. – dnlmzw Mar 29 '19 at 10:40