Skip to content
This repository has been archived by the owner on Oct 21, 2022. It is now read-only.

Latest commit

 

History

History
123 lines (89 loc) · 2.64 KB

mapDispatchToProps-returns-object.md

File metadata and controls

123 lines (89 loc) · 2.64 KB

Enforces that mapDispatchToProps returns an object. (react-redux/mapDispatchToProps-returns-object)

Enforces that the mapDispatchToProps is an object or a function returning an object.

*Note: All of the caught cases would have caused a runtime warning by react-redux *

Rule details

The following pattern is considered incorrect:

const mapDispatchToProps = (dispatch) => dispatch(action())
connect((state) => state, (dispatch) => dispatch(action()))(App)
const mapDispatchToProps = () => {}

The following patterns are considered correct:

const mapDispatchToProps = {}
const mapDispatchToProps = null;
const mapDispatchToProps = {anAction: anAction}
const mapDispatchToProps = (dispatch) => ({anAction: dispatch(anAction())})

Options

allowReturnBindFn

Rule example

{
  'react-redux/mapDispatchToProps-returns-object': ['error', { allowReturnBindFn: true }],
}

If this option is set to true, return the result of bindActionCreators considered to be valid:

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(
    {
      requestFilteredItems,
      showAlert: showAlertAction,
    },
    dispatch
  );
}

Not supported use cases.

mapDispatchToProps is a function but actions are not bound to dispatch

If a function is passed, it will be given dispatch as the first parameter. It’s up to you to return an object that somehow uses dispatch to bind action creators in your own way.

Below use case is likely not what you want but will not be enforced by this rule nor runtime react-redux check:

const mapDispatchToProps = () => ({
  action
});

In this scenario action wouldn't be wrapped in dispatch and thus wouldn't be triggered.

Most likely it needs to be rewritten as:

const mapDispatchToProps = {
  action
};

or

const mapDispatchToProps = (dispatch) => ({
  action: () => dispatch(action())
});

or

const mapDispatchToProps = (dispatch) => ({
  action: () => bindActionCreators(action, dispatch)
});

mapDispatchToProps is equal to or returns a variable

Note that if mapDispatchToProps is assigned a value of a variable there is no way for lint to know if the variable resolves to an object.

So both of below use cases will be considered correct by the rule event though the second one is technically incorrect.

This one would be caught by a react-redux check.

const actionsMap = {
  action1,
  action2,
};
const mapDispatchToProps = actionsMap;
const mapDispatchToProps = aSingleAction;