Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New rule proposal #2281

Closed
hornta opened this issue May 17, 2019 · 1 comment
Closed

New rule proposal #2281

hornta opened this issue May 17, 2019 · 1 comment

Comments

@hornta
Copy link

hornta commented May 17, 2019

This rule would report on unreachable code paths in React components.

Example: this.state.bar will never be truthy because there is no setState({ bar: ... }); and will make the code inside the condition unreachable.

Example of incorrect code

class Foo extends React.Component {
  constructor() {
    this.state = {
      bar: false
    };
  }

  render() {
    if(this.state.bar) {
      return 'bar'; // this is unreachable
    }
    return 'foo';
  }
}
function Foo() {
  const [bar, setBar] = useState(false);

  if(bar) {
    return 'bar'; // this is unreachable
  }

  return 'foo';
}
function Foo() {
  const [bar, setBar] = useState(false);

  setBar(null); // setting to null still makes the code unreachable

  if(bar) {
    return 'bar'; // this is unreachable
  }

  return 'foo';
}

Example of correct code

class Foo extends React.Component {
  constructor() {
    this.state = {
      bar: false
    };
  }

  componentDidMount() {
    this.setState({ bar: true }); // setting bar to a known non-falsy value
  }

  render() {
    if(this.state.bar) {
      return 'bar'; 
    }
    return 'foo';
  }
}
function Foo() {
  const [bar, setBar] = useState(false);

  setBar(returnWhat()); // because returnWhat can return a truthy value

  if(bar) {
    return 'bar'; // this may be reachable, we can't know
  }

  return 'foo';
}
@ljharb
Copy link
Member

ljharb commented May 18, 2019

That sounds very difficult to code reliably; since this.setState can be passed any object literal, which wouldn't be statically analyzeable - iow, any setState call that didn't have an object literal in it, or that had spread syntax in it, would make the rule useless for the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants