DianaSuvorova / eslint-plugin-react-redux

Enforcing best practices for react-redux

Home Page:https://www.npmjs.com/package/eslint-plugin-react-redux

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mapDispatchToProps-prefer-object triggering false positive on shorthand methods

calinoracation opened this issue · comments

One of the common errors I'm seeing is this rule throwing when we have a piece of code like the below that is returning an object:

const mapDispatchToProps = dispatch => ({
  onDoSomething: () => dispatch(toSomethingElse()),
});

My assumption was that one shouldn't define any special logic inside mapDispatchToProps, and that in above example you would need to create another action instead (ieonDoSomething ).
But I can see how this can be overly strict for some projects. Let me look into relaxing this rule to accommodate for the use case.

I think this rule needs to evolve into 2 independent checks instead:

  1. mapDispatchToProps-no-bindActionCreators
    Even though the react-redux docs provide tons of example with bindActionCreators, there should be no need for it and it may be rather confusing:

Normally you should just call dispatch directly on your Store instance. If you use Redux with React, react-redux will provide you with the dispatch function so you can call it directly, too.

The only use case for bindActionCreators is when you want to pass some action creators down to a component that isn't aware of Redux, and you don't want to pass dispatch or the Redux store to it.

source

  1. mapDispatchToProps-consistent-dispatch
    This rule would warn the following case:
const mapDispatchToProps = dispatch => ({
  onDoSomething: () => dispatch(toSomethingElse()),
  action1: action1
});

while below two are correct:

const mapDispatchToProps = dispatch => ({
  onDoSomething: () => dispatch(toSomethingElse()),
  action1: () => dispatch(action1())
});
const mapDispatchToProps = {
  onDoSomething: doSomethingElse
  action1,
});

Let me know your thoughts

Oh, and one more rule:

  1. mapDispatchToProps-prefer-shorthand.

This would warn:

const mapDispatchToProps = dispatch => ({
  onDoSomething: () => dispatch(onDoSomething()),
  action1: () => dispatch(action1()),
  action2: (arg1, arg2) => dispatch(action2(arg1, arg2)),
});

because this can be affectively rewritten as:

const mapDispatchToProps = {
  onDoSomething,
  action1,
  action2,
});

and If there is any logic , the rule will consider the usage correct

const mapDispatchToProps = dispatch => ({
  onDoSomething: () => dispatch(onDoSomethingElse()),
  action1: () => dispatch(action1()),
  action2: (arg1, arg2) => dispatch(action2(arg1 + arg2)),
});

Will close this. Created #24 for the only remaining action item.