2.0.1 • Published 7 years ago

react-set-state-usage v2.0.1

Weekly downloads
8
License
MIT
Repository
github
Last release
7 years ago

react-set-state-usage CircleCI npm version PRs Welcome

react-set-state-usage is a rule, that enforces usage of callbacks in setState calls instead of objects. Moreover, it forbids access to this.props and this.state within setState(...) calls.

  • updater-only: it also has updater-only option to forbid usage of second callback parameter of setState

Installation

react-set-state-usage is available as the react-set-state-usage package on npm.

Usage

Extend this tslint plugin in the tslint.json file and update the rules as displayed in the following code:

{
  "extends": [
    "react-set-state-usage"
  ],
  "rules": {
    "react-set-state-usage": true
  },
}

To enable the updater-only option, rule should be used like this:

"rules:" {
  "react-set-state-usage": [true, "updater-only"]
}

Examples

class NameDemo extends React.Component<{ someFlag: boolean, someCallback: () => void }, { redundandFlag: boolean, name: string }> {

  constructor(props) {
    super(props);

    this.state = { name: 'initialName' };

    this.onBadClick = this.onBadClick.bind(this);
    this.onGoodClick = this.onGoodClick.bind(this);
    this.onSomeOtherClick = this.onSomeOtherClick.bind(this);
  }

  function onBadClick() {
    this.setState({ name: 'badName' });  // will produce tslint error
    this.setState({ redundandFlag: this.props.flag });  // will produce tslint error, same holds for 'this.state' access
  }
  
  function onGoodClick() {
    this.setState(() => ({ name: 'goodName' })); // will not produce tslint error
    this.setState((state, props) => ({ redundandFlag: props.flag })); // will not produce tslint error
  }
  
  function onSomeOtherClick() {
    this.setState(() => ({ name: 'someName' }), this.props.someCallback); // with updater-only option enabled, will produce tslint error
  }

  render() {
    return (
      <div>
        <span>{this.state.name}</span>
        <button onClick={this.onBadClick}> bad button </button>
        <button onClick={this.onGoodClick}> good button </button>
        <button onClick={this.onSomeOtherClick}> some button </button>
      </div>
    );
  }
}
2.0.1

7 years ago

2.0.0

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago