Skip to content

Commit 4950623

Browse files
committed
Make no-access-state-in-setstate find cases where state is destructured from this
1 parent 73f135a commit 4950623

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

lib/rules/no-access-state-in-setstate.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ module.exports = {
107107
if (current.type === 'VariableDeclarator') {
108108
vars.push({
109109
node: node,
110-
scope: context.getScope()
110+
scope: context.getScope(),
111+
variableName: current.id.name
111112
});
112113
break;
113114
}
@@ -123,11 +124,14 @@ module.exports = {
123124
while (current.parent.type === 'BinaryExpression') {
124125
current = current.parent;
125126
}
126-
if (current.parent.value === current) {
127+
if (
128+
current.parent.value === current ||
129+
current.parent.object === current
130+
) {
127131
while (current.type !== 'Program') {
128132
if (isSetStateCall(current)) {
129133
vars
130-
.filter(v => v.scope === context.getScope())
134+
.filter(v => v.scope === context.getScope() && v.variableName === node.name)
131135
.map(v => context.report(
132136
v.node,
133137
'Use callback in setState when referencing the previous state.'
@@ -136,6 +140,19 @@ module.exports = {
136140
current = current.parent;
137141
}
138142
}
143+
},
144+
145+
ObjectPattern(node) {
146+
const isDerivedFromThis = node.parent.init.type === 'ThisExpression';
147+
node.properties.forEach(property => {
148+
if (property.key.name === 'state' && isDerivedFromThis) {
149+
vars.push({
150+
node: property.key,
151+
scope: context.getScope(),
152+
variableName: property.key.name
153+
});
154+
}
155+
});
139156
}
140157
};
141158
}

0 commit comments

Comments
 (0)