There is no direct API in mapDispachToProps
available to access the store.
If you need the store state to dispatch actions, you typically use some sort of Redux middleware like Redux Thunk. The concrete library isn't important, you even could apply your own middleware to Redux, whose sole purpose is to additionally receive the state in a callback. What matters is that you decouple the concrete store instance from the UI layer in order to abstract complex logic involving state and action creation away and make the system better testable.
Simple example with Redux Thunk
You can return a callback function as return of the dispatch that receives getState
besides dispatch
as arguments.
const mapDispachToProps = (dispatch) => {
return {
...
onSetValue: e => dispatch(setPasswordOrUser(e));
};
};
const setPasswordOrUser = e => (dispatch, getState) => {
// do something with getState
if (e.target.name==="password"){
dispatch({ type: "Set Password", value: e.target.value })
} else if (e.target.name==="username") {
dispatch({ type: "Set User", value: e.target.value })
}
}
Other approaches
Alternative 1: receive the store via React Context (ReactReduxContext Consumer) directly. React Redux is based on Context API which can pass down the store in the component tree, e.g to mapDispatchToProps
via ownProps argument.
Alternative 2: expose store
/state
as singleton module export like this:
// store.js
import { createStore } from 'redux'
let store = createStore(rootReducer)
export const getState = store.getState
// client.js
import { getState } from "./store"
Big disadvantage here is, that you couple your store instance to React/UI layer, it's easy to mix up architecture layer responsibilities and distribute code dealing with the store in many code locations.
The whole purpose of mapDispatchToProps
is to abstract dispatch
away from the components. I would really encourage you to use some form of middleware for action dispatching that involves the store state. The other approaches come along with architecture costs.