Baz Baz - 2 months ago 15
React JSX Question

Action dependant on data from another state

I have a react-redux app with 3 reducers:

clientPrivileges
,
userFilter
and
userData
acting on my store.

A table component is used to present the data for each user and a drop down component is used to filter this table for specific users. When the drop down is selected for a specific user I need to call the backend to retrieve the data. This is the action associated with this:

selectUser(userId, dispatch) {
api.getUserData(userId, accessTypeId, (data) => {
dispatch(userActions.update(data));
});

return{
type: selectUser,
userId
}
}


However you can see that I have an argument called
accessTypeId
which needs to be sent to the backend as well as the
userId
. This value has been set in the store using the
clientPrivileges
reducer on login to the app.

I can't see any other way other than setting
accessTypeId
as a prop for the drop-down component in its
mapStateToProps
. And then in the component itself:

this.props.users.map(u => {

function onClick()
{
selectEndUserGroup(u.id, this.props.accessTypeId);
}
return <div id={"filter_group_"+u.id} key={u.id} onClick={onClick}>{name}</div>


But now I've destroyed my generic drop-down component with an
accessTypeId
property. How should I be doing this?

Answer

If I'm understanding correctly, you want your action to have access to a value stored in the Redux state, yes?

Redux-Thunk handles this nicely. The code would look something like this;

selectUser(userId) {
    return function(dispatch, getState){

        var accessTypeId = getState().[PATH TO REDUX STATE ELEMENT]
        api.getUserData(userId, accessTypeId, (data) => {
            dispatch(userActions.update(data));
        });

        dispatch({
            type: selectUser,
            userId
        })
    }
}