Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access State inside of mapDispatchToProps method

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?

like image 702
Knows Not Much Avatar asked Mar 07 '16 04:03

Knows Not Much


People also ask

Is state accessible in mapDispatchToProps?

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.

What do mapStateToProps and mapDispatchToProps actually do?

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.

When mapDispatchToProps is called?

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.

Is it possible to dispatch an action without using mapDispatchToProps?

Without mapDispatchToPropsNotice that the component receives a dispatch prop, which comes from connect() , and then has to use it directly to trigger the actions.


1 Answers

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.

like image 64
markerikson Avatar answered Sep 18 '22 08:09

markerikson