Skip to content

Commit

Permalink
Add prevState and nextState support to no-unused-state (fixes #1759)
Browse files Browse the repository at this point in the history
  • Loading branch information
yannickcr committed May 9, 2018
1 parent 3aac310 commit b26d1cc
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ module.exports = {
// JSX attributes), then this is again set to null.
let classInfo = null;

// Returns true if the given node is possibly a reference to `this.state`.
// Returns true if the given node is possibly a reference to `this.state`, `prevState` or `nextState`.
function isStateReference(node) {
node = uncast(node);

Expand All @@ -91,7 +91,15 @@ module.exports = {
classInfo.aliases &&
classInfo.aliases.has(node.name);

return isDirectStateReference || isAliasedStateReference;
const isPrevStateReference =
node.type === 'Identifier' &&
node.name === 'prevState';

const isNextStateReference =
node.type === 'Identifier' &&
node.name === 'nextState';

return isDirectStateReference || isAliasedStateReference || isPrevStateReference || isNextStateReference;
}

// Takes an ObjectExpression node and adds all named Property nodes to the
Expand Down
43 changes: 43 additions & 0 deletions tests/lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,49 @@ eslintTester.run('no-unused-state', rule, {
}
}`,
parser: 'babel-eslint'
},
{
code: `class ESLintExample extends Component {
constructor(props) {
super(props);
this.state = {
id: 123,
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.id === nextProps.id) {
return {
selected: true,
};
}
return null;
}
render() {
return (
<h1>{this.state.selected ? 'Selected' : 'Not selected'}</h1>
);
}
}`,
parser: 'babel-eslint'
},
{
code: `class ESLintExample extends Component {
constructor(props) {
super(props);
this.state = {
id: 123,
};
}
shouldComponentUpdate(nextProps, nextState) {
return nextState.id === nextProps.id;
}
render() {
return (
<h1>{this.state.selected ? 'Selected' : 'Not selected'}</h1>
);
}
}`,
parser: 'babel-eslint'
}
],

Expand Down

0 comments on commit b26d1cc

Please sign in to comment.