Skip to content

Commit

Permalink
[Fix] no-unused-state: fix set state callback destructing & state u…
Browse files Browse the repository at this point in the history
…se inside callback
  • Loading branch information
Barak Yosipovich authored and ljharb committed Feb 2, 2019
1 parent 6a68f09 commit 4270205
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,19 @@ module.exports = {
} else if (
isSetStateCall(node) &&
node.arguments.length > 0 &&
node.arguments[0].type === 'ArrowFunctionExpression' &&
node.arguments[0].body.type === 'ObjectExpression'
node.arguments[0].type === 'ArrowFunctionExpression'
) {
if (node.arguments[0].body.type === 'ObjectExpression') {
addStateFields(node.arguments[0].body);
}
if (node.arguments[0].params.length > 0 && classInfo.aliases) {
classInfo.aliases.add(getName(node.arguments[0].params[0]));
const firstParam = node.arguments[0].params[0];
if (firstParam.type === 'ObjectPattern') {
handleStateDestructuring(firstParam);
} else {
classInfo.aliases.add(getName(firstParam));
}
}
addStateFields(node.arguments[0].body);
}
},

Expand Down
46 changes: 46 additions & 0 deletions tests/lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,52 @@ eslintTester.run('no-unused-state', rule, {
}
});
`
}, {
code: `
class SetStateDestructuringCallback extends Component {
state = {
used: 1, unused: 2
}
handleChange = () => {
this.setState(({unused}) => ({
used: unused * unused,
}));
}
render() {
return <div>{this.state.used}</div>
}
}
`,
parser: 'babel-eslint'
},
{
code: `
class SetStateCallbackStateCondition extends Component {
state = {
isUsed: true,
foo: 'foo'
}
handleChange = () => {
this.setState((prevState) => (prevState.isUsed ? {foo: 'bar', isUsed: false} : {}));
}
render() {
return <SomeComponent foo={this.state.foo} />;
}
}
`,
parser: 'babel-eslint'
}, {
// Don't error out
code: `
class Foo extends Component {
handleChange = function() {
this.setState(() => ({ foo: value }));
}
render() {
return <SomeComponent foo={this.state.foo} />;
}
}`,
parser: 'babel-eslint'
}, {
// Don't error out
code: `
Expand Down

0 comments on commit 4270205

Please sign in to comment.