Skip to content

Commit

Permalink
[Fix] no-unused-state: avoid crashing on a class field function wit…
Browse files Browse the repository at this point in the history
…h destructured state

Fixes #3568
  • Loading branch information
ljharb committed May 1, 2023
1 parent 0855e5f commit f2d8d26
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
* [`jsx-first-prop-new-line`]: ensure autofix preserves generics in component name ([#3546][] @ljharb)
* [`no-unknown-property`]: allow `fill` prop on `<symbol>` ([#3555][] @stefanprobst)
* [`display-name`], [`prop-types`]: when checking for a capitalized name, ignore underscores entirely ([#3560][] @ljharb)
* [`no-unused-state`]: avoid crashing on a class field function with destructured state ([#3568][] @ljharb)

[#3568]: https://github.com/jsx-eslint/eslint-plugin-react/issues/3568
[#3560]: https://github.com/jsx-eslint/eslint-plugin-react/issues/3560
[#3555]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3555
[#3548]: https://github.com/jsx-eslint/eslint-plugin-react/pull/3548
Expand Down
16 changes: 9 additions & 7 deletions lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -379,14 +379,16 @@ module.exports = {
}
const argVar = scope.variables.find((x) => x.name === stateArg.name);

const stateRefs = argVar.references;
if (argVar) {
const stateRefs = argVar.references;

stateRefs.forEach((ref) => {
const identifier = ref.identifier;
if (identifier && identifier.parent && identifier.parent.type === 'MemberExpression') {
addUsedStateField(identifier.parent.property);
}
});
stateRefs.forEach((ref) => {
const identifier = ref.identifier;
if (identifier && identifier.parent && identifier.parent.type === 'MemberExpression') {
addUsedStateField(identifier.parent.property);
}
});
}
},

'PropertyDefinition:exit'(node) {
Expand Down
15 changes: 15 additions & 0 deletions tests/lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,21 @@ eslintTester.run('no-unused-state', rule, {
parserOptions: {
sourceType: 'module',
},
},
{
code: `
class Component extends React.Component {
static getDerivedStateFromProps = ({value, disableAnimation}: ToggleProps, {isControlled, isOn}: ToggleState) => {
return { isControlled, isOn };
};
render() {
const { isControlled, isOn } = this.state;
return <div>{isControlled ? 'controlled' : ''}{isOn ? 'on' : ''}</div>;
}
}
`,
features: ['types', 'class fields'],
}
)),

Expand Down

0 comments on commit f2d8d26

Please sign in to comment.