0

I have a mapDispatchToProps function like this one below.

export function mapDispatchToProps(dispatch, ownProps) {
  return {
    handleChangeLang: changeLocaleDispatcher(dispatch),
    handleChange: handleChangeDispatcher(dispatch),
    handleSubmit: handleSubmitDispatcher(dispatch)
  }
}

I just added redux-thunk to my project so I can access state from my action creators (think that's the correct term).

It doesn't seem there's any documentation in redux-thunk outlining how to access getState from mapDispatchToProps. The docs dispatch using the store.dispatch method.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

3 Answers3

1

Your initial syntax is wrong, and the "hacky" example is also not how you should go about it.

A sample would look like:

import {thunkAction1, thunkAction2} from "myActions";
import {bindActionCreators} from "redux";

const mapDispatchToProps(dispatch) => {
    return {
        manuallyBoundAction : (...args) => dispatch(thunkAction1(...args)),
        autoBoundAction : bindActionCreators(thunkAction2, dispatch),
        multipleActionsTogether : bindActionCreators({thunkAction1, thunkAction2}, dispatch)
    }
};

And no, getState itself is not accessible inside mapDispatchToProps. It's available inside the thunk, but not mapDispatch.

You may want to read this answer on why thunks exist, as well as the Redux docs on async actions.

Community
  • 1
  • 1
markerikson
  • 63,178
  • 10
  • 141
  • 157
0

So while I don't see your current action creator in your question, I will assume it's ES6/ES2015 javascript.

The below should give you freedom to grab any state. Since you have redux-thunk, you should be good to go.

export function setActivity(activityName) {
  return function (dispatch, getState) {
    dispatch({
      type: SET_ACTIVITY,
      description: 'Set the name of the activity being done now',
      currentActivityName: activityName,
      currentActivityData: getState().activityStore.activities[activityName]
    });
  };
}

activityStore is same as what you've defined for that particular reducer, see below.

export const reducers = {
  activityStore: ActivityStore.reducer,
  someOtherStore: SomeOtherStore.reducer
};
William Bernting
  • 561
  • 4
  • 15
-1

Hacky fix :/

let ProvidedApp = (serverProps) => {

  let store = getStore(serverProps)

  let ConnectedApp = connect(
    mapStateToProps,
    mapDispatchToProps(store)
  )(App)

  return (
    <Provider store={store}>
      <ConnectedApp/>
    </Provider>
  )
}

export function mapDispatchToProps(store) {
  return (dispatch, ownProps) => {
    return {
      handleChangeLang: store.dispatch(changeLocaleDispatcher),
      handleChange:  store.dispatch(handleChangeDispatcher),
      handleSubmit: store.dispatch(handleSubmitDispatcher)
    }
  }
}
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424