Skip to content

Commit

Permalink
Merge pull request #1598 from jaaberg/master
Browse files Browse the repository at this point in the history
Find edge case in no-access-state-in-setstate (#1597)
  • Loading branch information
ljharb authored Dec 13, 2017
2 parents 292ebed + 4950623 commit a908eb3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
23 changes: 20 additions & 3 deletions lib/rules/no-access-state-in-setstate.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ module.exports = {
if (current.type === 'VariableDeclarator') {
vars.push({
node: node,
scope: context.getScope()
scope: context.getScope(),
variableName: current.id.name
});
break;
}
Expand All @@ -123,11 +124,14 @@ module.exports = {
while (current.parent.type === 'BinaryExpression') {
current = current.parent;
}
if (current.parent.value === current) {
if (
current.parent.value === current ||
current.parent.object === current
) {
while (current.type !== 'Program') {
if (isSetStateCall(current)) {
vars
.filter(v => v.scope === context.getScope())
.filter(v => v.scope === context.getScope() && v.variableName === node.name)
.map(v => context.report(
v.node,
'Use callback in setState when referencing the previous state.'
Expand All @@ -136,6 +140,19 @@ module.exports = {
current = current.parent;
}
}
},

ObjectPattern(node) {
const isDerivedFromThis = node.parent.init.type === 'ThisExpression';
node.properties.forEach(property => {
if (property.key.name === 'state' && isDerivedFromThis) {
vars.push({
node: property.key,
scope: context.getScope(),
variableName: property.key.name
});
}
});
}
};
}
Expand Down
24 changes: 24 additions & 0 deletions tests/lib/rules/no-access-state-in-setstate.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ ruleTester.run('no-access-state-in-setstate', rule, {
});
`,
parserOptions: parserOptions
}, {
code: [
'var Hello = React.createClass({',
' onClick: function() {',
' var nextValueNotUsed = this.state.value + 1',
' var nextValue = 2',
' this.setState({value: nextValue})',
' }',
'});'
].join('\n'),
parserOptions: parserOptions
}],

invalid: [{
Expand Down Expand Up @@ -103,6 +114,19 @@ ruleTester.run('no-access-state-in-setstate', rule, {
errors: [{
message: 'Use callback in setState when referencing the previous state.'
}]
}, {
code: [
'var Hello = React.createClass({',
' onClick: function() {',
' var {state} = this',
' this.setState({value: state.value + 1})',
' }',
'});'
].join('\n'),
parserOptions: parserOptions,
errors: [{
message: 'Use callback in setState when referencing the previous state.'
}]
}, {
code: [
'function nextState(state) {',
Expand Down

0 comments on commit a908eb3

Please sign in to comment.