Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ function getInitialClassInfo() {
};
}

function isSetStateCall(node) {
return (
node.callee.type === 'MemberExpression' &&
isThisExpression(node.callee.object) &&
getName(node.callee.property) === 'setState'
);
}

module.exports = {
meta: {
docs: {
Expand Down Expand Up @@ -246,13 +254,21 @@ module.exports = {
// If we're looking at a `this.setState({})` invocation, record all the
// properties as state fields.
if (
node.callee.type === 'MemberExpression' &&
isThisExpression(node.callee.object) &&
getName(node.callee.property) === 'setState' &&
isSetStateCall(node) &&
node.arguments.length > 0 &&
node.arguments[0].type === 'ObjectExpression'
) {
addStateFields(node.arguments[0]);
} else if (
isSetStateCall(node) &&
node.arguments.length > 0 &&
node.arguments[0].type === 'ArrowFunctionExpression' &&
node.arguments[0].body.type === 'ObjectExpression'
) {
if (node.arguments[0].params.length > 0) {
classInfo.aliases.add(getName(node.arguments[0].params[0]));
}
addStateFields(node.arguments[0].body);
}
},

Expand Down
79 changes: 79 additions & 0 deletions tests/lib/rules/no-unused-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,66 @@ eslintTester.run('no-unused-state', rule, {
}
}`,
parser: 'babel-eslint'
}, {
code: `
class Foo extends Component {
state = {
initial: 'foo',
}
handleChange = () => {
this.setState(state => ({
current: state.initial
}));
}
render() {
const { current } = this.state;
return <div>{current}</div>
}
}
`,
parser: 'babel-eslint'
}, {
code: `
class Foo extends Component {
constructor(props) {
super(props);
this.state = {
initial: 'foo',
}
}
handleChange = () => {
this.setState(state => ({
current: state.initial
}));
}
render() {
const { current } = this.state;
return <div>{current}</div>
}
}
`,
parser: 'babel-eslint'
}, {
code: `
class Foo extends Component {
constructor(props) {
super(props);
this.state = {
initial: 'foo',
}
}
handleChange = () => {
this.setState((state, props) => ({
current: state.initial
}));
}
render() {
const { current } = this.state;
return <div>{current}</div>
}
}
`,
parser: 'babel-eslint'
}
],

Expand Down Expand Up @@ -914,6 +974,25 @@ eslintTester.run('no-unused-state', rule, {
}`,
errors: getErrorMessages(['id']),
parser: 'babel-eslint'
}, {
code: `
class Foo extends Component {
state = {
initial: 'foo',
}
handleChange = () => {
this.setState(() => ({
current: 'hi'
}));
}
render() {
const { current } = this.state;
return <div>{current}</div>
}
}
`,
parser: 'babel-eslint',
errors: getErrorMessages(['initial'])
}
]
});