Skip to content

Accept object as connect's mapStateToProps argument? #594

@alsiola

Description

@alsiola

We can currently call connect with an object argument for mapDispatchToProps, where each function in the object is assumed to be an actioncreator. Could a similar option be available for mapStateToProps, where it would be assumed that each function in the object would be a selector? This could then be used as, for example:

import { connect } from 'react-redux';
import { actionCreator1, actionCreator2 } from './ActionCreators';
import { selector1, selector2 } user from './Selectors';
import PresentationalComponent from './PresentationalComponent';

export default connect(
    { 
        selector1,
        selector2
    },
    {
        actionCreator1,
        actionCreator2
    }    
)( PresentationalComponent );

I am currently achieving this with the following:

import { connect } from 'react-redux';

export default (originalStateToProps, dispatchToProps) => {

    let updatedStateToProps = originalStateToProps;

    if (typeof originalStateToProps !== "function") {
        updatedStateToProps = (state, ownProps) => {
            let mappedProps = {};
            for (const key in originalStateToProps) {
                if (originalStateToProps.hasOwnProperty(key)) {
                    mappedProps[key] = originalStateToProps[key](state, ownProps);
                }
            }
            return mappedProps;
        }
    }   
    
    return connect( updatedStateToProps, dispatchToProps );
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions