Skip to content

Commit

Permalink
[Fix] no-unused-state: avoid a crash
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Apr 3, 2022
1 parent b9b1bee commit 74d2e35
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
### Fixed
* [`hook-use-state`]: Allow UPPERCASE setState setter prefixes ([#3244][] @duncanbeevers)
* `propTypes`: add `VFC` to react generic type param map ([#3230][] @dlech)
* [`no-unused-state`]: avoid a crash (@ljharb)

### Changed
* [readme] remove global usage and eslint version from readme ([#3254][] @aladdin-add)
Expand Down
3 changes: 3 additions & 0 deletions lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,9 @@ module.exports = {
// Adds the name of the given node as a used state field if the node is an
// Identifier or a Literal. Other node types are ignored.
function addUsedStateField(node) {
if (!classInfo) {
return;
}
const name = getName(node);
if (name) {
classInfo.usedStateFields.add(name);
Expand Down
42 changes: 38 additions & 4 deletions tests/lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -989,16 +989,16 @@ eslintTester.run('no-unused-state', rule, {
semver.satisfies(tsEslintVersion, '>= 5') ? {
code: `
interface Props {}
interface State {
flag: boolean;
}
export default class RuleTest extends React.Component<Props, State> {
readonly state: State = {
flag: false,
};
static getDerivedStateFromProps = (props: Props, state: State) => {
const newState: Partial<State> = {};
if (!state.flag) {
Expand Down Expand Up @@ -1030,7 +1030,7 @@ eslintTester.run('no-unused-state', rule, {
class KarmaRefundPillComponent extends GenericPillComponent {
renderContent = () => {
const { action } = this.props
return (
<Box fontSize={[1]} mx={[2]} minWidth="10px" minHeight="26px" alignItems="center">
<FormattedText
Expand Down Expand Up @@ -1064,6 +1064,40 @@ eslintTester.run('no-unused-state', rule, {
parserOptions: {
sourceType: 'module',
},
},
{
code: `
import React, { PureComponent } from 'react';
class TestNoUnusedState extends React.Component {
constructor(props) {
super(props);
this.state = {
id: null,
};
}
static getDerivedStateFromProps = (props, state) => {
if (state.id !== props.id) {
return {
id: props.id,
};
}
return null;
};
render() {
return <h1>{this.state.id}</h1>;
}
}
export default TestNoUnusedState;
`,
features: ['class fields'],
parserOptions: {
sourceType: 'module',
},
}
)),

Expand Down

0 comments on commit 74d2e35

Please sign in to comment.