Skip to content

Commit 4270205

Browse files
barakyosiljharb
authored andcommitted
[Fix] no-unused-state: fix set state callback destructing & state use inside callback
1 parent 6a68f09 commit 4270205

File tree

2 files changed

+56
-4
lines changed

2 files changed

+56
-4
lines changed

lib/rules/no-unused-state.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,13 +262,19 @@ module.exports = {
262262
} else if (
263263
isSetStateCall(node) &&
264264
node.arguments.length > 0 &&
265-
node.arguments[0].type === 'ArrowFunctionExpression' &&
266-
node.arguments[0].body.type === 'ObjectExpression'
265+
node.arguments[0].type === 'ArrowFunctionExpression'
267266
) {
267+
if (node.arguments[0].body.type === 'ObjectExpression') {
268+
addStateFields(node.arguments[0].body);
269+
}
268270
if (node.arguments[0].params.length > 0 && classInfo.aliases) {
269-
classInfo.aliases.add(getName(node.arguments[0].params[0]));
271+
const firstParam = node.arguments[0].params[0];
272+
if (firstParam.type === 'ObjectPattern') {
273+
handleStateDestructuring(firstParam);
274+
} else {
275+
classInfo.aliases.add(getName(firstParam));
276+
}
270277
}
271-
addStateFields(node.arguments[0].body);
272278
}
273279
},
274280

tests/lib/rules/no-unused-state.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,52 @@ eslintTester.run('no-unused-state', rule, {
670670
}
671671
});
672672
`
673+
}, {
674+
code: `
675+
class SetStateDestructuringCallback extends Component {
676+
state = {
677+
used: 1, unused: 2
678+
}
679+
handleChange = () => {
680+
this.setState(({unused}) => ({
681+
used: unused * unused,
682+
}));
683+
}
684+
render() {
685+
return <div>{this.state.used}</div>
686+
}
687+
}
688+
`,
689+
parser: 'babel-eslint'
690+
},
691+
{
692+
code: `
693+
class SetStateCallbackStateCondition extends Component {
694+
state = {
695+
isUsed: true,
696+
foo: 'foo'
697+
}
698+
handleChange = () => {
699+
this.setState((prevState) => (prevState.isUsed ? {foo: 'bar', isUsed: false} : {}));
700+
}
701+
render() {
702+
return <SomeComponent foo={this.state.foo} />;
703+
}
704+
}
705+
`,
706+
parser: 'babel-eslint'
707+
}, {
708+
// Don't error out
709+
code: `
710+
class Foo extends Component {
711+
handleChange = function() {
712+
this.setState(() => ({ foo: value }));
713+
}
714+
render() {
715+
return <SomeComponent foo={this.state.foo} />;
716+
}
717+
}`,
718+
parser: 'babel-eslint'
673719
}, {
674720
// Don't error out
675721
code: `

0 commit comments

Comments
 (0)