Skip to content

Commit

Permalink
Fix no-direct-mutation-state detection with nested components (fixes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
yannickcr committed Aug 20, 2017
1 parent 6af4bca commit 9805f70
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
27 changes: 16 additions & 11 deletions lib/rules/no-direct-mutation-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,25 @@ module.exports = {
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
let inConstructor = false;
let inCallExpression = false;

return {
MethodDefinition(node) {
if (node.kind === 'constructor') {
inConstructor = true;
components.set(node, {
inConstructor: true
});
}
},

CallExpression: function() {
inCallExpression = true;
CallExpression: function(node) {
components.set(node, {
inCallExpression: true
});
},

AssignmentExpression(node) {
let item;
if ((inConstructor && !inCallExpression) || !node.left || !node.left.object) {
const component = components.get(utils.getParentComponent());
if (!component || (component.inConstructor && !component.inCallExpression) || !node.left || !node.left.object) {
return;
}
item = node.left;
Expand All @@ -75,7 +77,6 @@ module.exports = {
item.object.type === 'ThisExpression' &&
item.property.name === 'state'
) {
const component = components.get(utils.getParentComponent());
const mutations = (component && component.mutations) || [];
mutations.push(node.left.object);
components.set(node, {
Expand All @@ -85,13 +86,17 @@ module.exports = {
}
},

'CallExpression:exit': function() {
inCallExpression = false;
'CallExpression:exit': function(node) {
components.set(node, {
inCallExpression: false
});
},

'MethodDefinition:exit': function (node) {
if (node.kind === 'constructor') {
inConstructor = false;
components.set(node, {
inConstructor: false
});
}
},

Expand Down
14 changes: 14 additions & 0 deletions tests/lib/rules/no-direct-mutation-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,20 @@ ruleTester.run('no-direct-mutation-state', rule, {
' }',
'}'
].join('\n')
}, {
code: `
class OneComponent extends Component {
constructor() {
super();
class AnotherComponent extends Component {
constructor() {
super();
}
}
this.state = {};
}
}
`
}],

invalid: [{
Expand Down

0 comments on commit 9805f70

Please sign in to comment.