Skip to content

Handle UpdateExpressions in no-direct-mutation-state #1387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 11, 2017
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
59 changes: 49 additions & 10 deletions lib/rules/no-direct-mutation-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,36 @@ module.exports = {
}
}

/**
* Walks throughs the MemberExpression to the top-most property.
* @param {Object} node The node to process
* @returns {Object} The outer-most MemberExpression
*/
function getOuterMemberExpression(node) {
while (node.object && node.object.property) {
node = node.object;
}
return node;
}

/**
* Determine if this MemberExpression is for `this.state`
* @param {Object} node The node to process
* @returns {Boolean}
*/
function isStateMemberExpression(node) {
return node.object.type === 'ThisExpression' && node.property.name === 'state';
}

/**
* Determine if we should currently ignore assignments in this component.
* @param {?Object} component The component to process
* @returns {Boolean} True if we should skip assignment checks.
*/
function shouldIgnoreComponent(component) {
return !component || (component.inConstructor && !component.inCallExpression);
}

// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
Expand All @@ -64,19 +94,12 @@ module.exports = {
},

AssignmentExpression(node) {
let item;
const component = components.get(utils.getParentComponent());
if (!component || (component.inConstructor && !component.inCallExpression) || !node.left || !node.left.object) {
if (shouldIgnoreComponent(component) || !node.left || !node.left.object) {
return;
}
item = node.left;
while (item.object && item.object.property) {
item = item.object;
}
if (
item.object.type === 'ThisExpression' &&
item.property.name === 'state'
) {
const item = getOuterMemberExpression(node.left);
if (isStateMemberExpression(item)) {
const mutations = (component && component.mutations) || [];
mutations.push(node.left.object);
components.set(node, {
Expand All @@ -86,6 +109,22 @@ module.exports = {
}
},

UpdateExpression(node) {
const component = components.get(utils.getParentComponent());
if (shouldIgnoreComponent(component) || node.argument.type !== 'MemberExpression') {
return;
}
const item = getOuterMemberExpression(node.argument);
if (isStateMemberExpression(item)) {
const mutations = (component && component.mutations) || [];
mutations.push(item);
components.set(node, {
mutateSetState: true,
mutations
});
}
},

'CallExpression:exit': function(node) {
components.set(node, {
inCallExpression: false
Expand Down
20 changes: 20 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,14 @@ ruleTester.run('no-direct-mutation-state', rule, {
' }',
'}'
].join('\n')
}, {
code: [
'class Hello extends React.Component {',
' constructor() {',
' this.state.foo = 1;',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we also add a test that makes ++ invalid inside the constructor?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh shoot, I must have missed adding that line checking another thing… Sorry.

I had this.state.foo++ right here as a valid case - we're in the constructor and while I think it's awkward, it's legal.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see why it should be legal; it's mutating this.state after it's assigned.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Assignment doesn't actually matter until we're out of the constructor method. That's when React takes over.

But that's also a tangential change to what I wanted to make here - I'm bringing ++ to parity with = (you have a test case immediately above this one showing that). If you want to change how you treat assignment as well, that's fine but I think you probably want to do that distinctly.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair enough.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been my favorite find in our codebase where we were assigning to state.

this.setState({
  foo: this.state.foo++
});

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TheSavior (cc: @zpao )

I actually have a PR proposing a rule catching all references to this.state used in at this.setState in #1374. Does this rule cover that as well? If not, I would be really happy for feedback.

' }',
'}'
].join('\n')
}, {
code: `
class OneComponent extends Component {
Expand Down Expand Up @@ -97,6 +105,18 @@ ruleTester.run('no-direct-mutation-state', rule, {
errors: [{
message: 'Do not mutate state directly. Use setState().'
}]
}, {
code: [
'var Hello = createReactClass({',
' render: function() {',
' this.state.foo++;',
' return <div>Hello {this.props.name}</div>;',
' }',
'});'
].join('\n'),
errors: [{
message: 'Do not mutate state directly. Use setState().'
}]
}, {
code: [
'var Hello = createReactClass({',
Expand Down