tslint-react-set-state-usage

2.0.2 • Public • Published

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

tslint-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

tslint-react-set-state-usage is available as the tslint-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": [
    "tslint-react-set-state-usage"
  ],
  "rules": {
    "tslint-react-set-state-usage": true
  }
}

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

"rules:" {
  "tslint-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>
    );
  }
}

/tslint-react-set-state-usage/

    Package Sidebar

    Install

    npm i tslint-react-set-state-usage

    Weekly Downloads

    22

    Version

    2.0.2

    License

    MIT

    Unpacked Size

    27.9 kB

    Total Files

    17

    Last publish

    Collaborators

    • sutrkiller