Access State inside of mapDispatchToProps method

Viewed 38065

I have written a container component using redux and my implementation for mapDispatchToProps looks like this

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onChange: (newValue) => {
            dispatch(updateAttributeSelection('genre', newValue));
            dispatch(getTableData(newValue, ownProps.currentYear));
        }
    }
}

The problem is that in order to getTableData I need the state of some other components. How can I get access to the state object in this method?

5 Answers

Possible approach is also to use mergeProps that merges mapState and mapDispatch and allows to use both at the same time.

// Define mapState
const mapState = (state) => ({
  needeedValue: state.neededValue
})

// Define mapDispatch
const mapDispatch = (dispatch, ownProps) => {
  return {
    onChange: (newValue, neededValue) => {
      dispatch(updateAttributeSelection('genre', newValue));
      dispatch(getTableData(newValue, ownProps.currentYear, neededValue));
    }
  }
}

// Merge it all (create final props to be passed)
const mergeProps = (stateProps, dispatchProps, ownProps) => {
  return {
    ...stateProps,  // optional
    ...dispatchProps,  // optional
    onChangeWithNeededValue: (newValue) => (
      dispatchProps.onChange(
        newValue,
        stateProps.needeedValue  // <<< here the magic happens
      )
    )
  }
}

// Pass mergePros to connect
const MyContainer = connect(mapState, mapDispatch, mergeProps)(MyComponent);

Official documentation: react-redux#connect

Possible performance drawback on larger apps: Stack Overflow - Performances and mergeProps in Redux

If you have used Thunk Middleware then you can write helper function into your Action.Js

export const getSearchedText =  () => (dispatch, getState) => {
    const { app } = getState();
    return app.searchedText;
}

If you have been used the container design pattern, your property container should be below

Container.js

export const mapDispatchToProps = (dispatch, ownProps) => {
    return {
             setSearch: search => {
                 var searchedText = dispatch(getSearchedText());
             }
}
Related