I want to dispatch an action to update my application's global state with the currently signed in user. When a user clicks a button, an event handler fires that is registered in mapDispatchToProps
, and then I want to dispatch an action (article.updateAuthor(currentUser)
). However, In mapDispatchToProps
I have no access to the state to get the current user, and I do not want to arbitrarily pass the currently signed in user to a component prop -- only to be passed to the click event above, which will then pass the user data to a dispatched action.
I know I can dispatch an action with a redux thunk which gives me access to the state. However, this seems rather heavy handed seeing as there are no API calls being made.
Has anyone ran into this problem before?
In the connect
function provided by react-redux
you have four optional arguments you can use:
mapStateToProps
mapDispatchToProps
mergeProps
(this one will give you what you want)options
From the documentation for mergeProps
:
If specified, it is passed the result of mapStateToProps(), mapDispatchToProps(), and the parent props. The plain object you return from it will be passed as props to the wrapped component. You may specify this function to select a slice of the state based on props, or to bind action creators to a particular variable from props
So in your case you'll use mapStateToProps
to access what ever portion of the global state you need. The result will be passed to mergeProps
as the stateProps
argument.
In mergeProps
do what you need to do with this state, use the result of dispatchProps
(or destructure dispatch
from it) and return the object you need in the component you want to connect to.