Access State inside of mapDispatchToProps method

Knows Not Much picture Knows Not Much · Mar 7, 2016 · Viewed 29.7k times · Source

I have written a container component using redux and my implementation for mapDispathToProps 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?

Answer

markerikson picture markerikson · Mar 7, 2016

You can use redux-thunk to create a separate action creator function which has access to getState, rather than defining the function inside mapDispatchToProps:

function doTableActions(newValue, currentYear) {
    return (dispatch, getState) => {
        dispatch(updateAttributeSelection('genre', newValue));
        let state = getState();
        // do some logic based on state, and then:
        dispatch(getTableData(newValue, currentYear));
    }
}


let mapDispatchToProps = (dispatch, ownProps) => {
    return {
        onChange : (newValue) => {
            dispatch(doTableActions(newValue, ownProps.currentYear))
        }
    }
}

Some varying ways to go about organizing those, but something like that ought to work.