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?
I think the real use case for accessing the state in mapDispatchToProps is to know which actions are available at runtime. For example you could map every possible action to a function and call it to dispatch the action or test it with an if clause to check whether the action is available.
The mapStateToProps and mapDispatchToProps deals with your Redux store's state and dispatch , respectively. state and dispatch will be supplied to your mapStateToProps or mapDispatchToProps functions as the first argument.
The mapDispatchToProps function will be called with dispatch as the first argument. You will normally make use of this by returning new functions that call dispatch() inside themselves, and either pass in a plain action object directly or pass in the result of an action creator.
Without mapDispatchToPropsNotice that the component receives a dispatch prop, which comes from connect() , and then has to use it directly to trigger the actions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With