Skip to content
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

Add "ctors" option to @no-direct-mutation-state" rule #1355

Closed
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
15 changes: 15 additions & 0 deletions docs/rules/no-direct-mutation-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,18 @@ class Hello extends React.Component {
}
}
```

## Rule Options

This rule can take one argument to ignore some specific props during validation.

```js
...
"react/no-direct-mutation-state": [<enabled>, {
constructors: <constructors>
}]
...
```

* `enabled`: for enabling the rule. 0=off, 1=warn, 2=error. Defaults to 0.
* `constructors`: optional array of methods name to check like constructor
48 changes: 41 additions & 7 deletions lib/rules/no-direct-mutation-state.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,26 @@ module.exports = {
description: 'Prevent direct mutation of this.state',
category: 'Possible Errors',
recommended: true
}
},

schema: [{
type: 'object',
properties: {
constructors: {
type: 'array',
items: {
type: 'string'
}
}
},
additionalProperties: false
}]
},

create: Components.detect((context, components, utils) => {
const configuration = context.options[0] || {};
const ctorsMethod = configuration.constructors || [];

/**
* Checks if the component is valid
* @param {Object} component The component to process
Expand All @@ -30,6 +46,24 @@ module.exports = {
return Boolean(component && !component.mutateSetState);
}

/**
* Checks if the method is ignored
* @param {String} name Name of the method to check.
* @returns {Boolean} True if the method is ignored, false if not.
*/
function isCtorMethod(name) {
return ctorsMethod.indexOf(name) !== -1;
}

/**
* Checks if the node is constructor or ignored
* @param {ASTNode} node The AST node being checked.
* @returns {Boolean} True if the method is is constructor or ignored, false if not.
*/
function isConstructor(node) {
return node.kind === 'constructor' || (node.kind === 'method' && isCtorMethod(node.key.name));
}

/**
* Reports undeclared proptypes for a given component
* @param {Object} component The component to process
Expand All @@ -48,13 +82,13 @@ module.exports = {
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
let inConstructor = false;
let inConstructorOrIgnored = false;
let inCallExpression = false;

return {
MethodDefinition(node) {
if (node.kind === 'constructor') {
inConstructor = true;
if (isConstructor(node)) {
inConstructorOrIgnored = true;
}
},

Expand All @@ -64,7 +98,7 @@ module.exports = {

AssignmentExpression(node) {
let item;
if ((inConstructor && !inCallExpression) || !node.left || !node.left.object) {
if ((inConstructorOrIgnored && !inCallExpression) || !node.left || !node.left.object) {
return;
}
item = node.left;
Expand All @@ -90,8 +124,8 @@ module.exports = {
},

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

Expand Down
25 changes: 25 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,17 @@ ruleTester.run('no-direct-mutation-state', rule, {
' }',
'}'
].join('\n')
}, {
code: [
'class Hello extends React.Component {',
' myMethod() {',
' this.state = {' +
' boo: "bar" ' +
' };' +
' }',
'}'
].join('\n'),
options: [{constructors: ['myMethod']}]
}],

invalid: [{
Expand Down Expand Up @@ -154,6 +165,20 @@ ruleTester.run('no-direct-mutation-state', rule, {
errors: [{
message: 'Do not mutate state directly. Use setState().'
}]
}, {
code: [
'class Hello extends React.Component {',
' myMethod(props) {',
' doSomethingAsync(() => {',
' this.state = "bad";',
' });',
' }',
'}'
].join('\n'),
options: [{constructors: ['myMethod']}],
errors: [{
message: 'Do not mutate state directly. Use setState().'
}]
}, {
code: [
'class Hello extends React.Component {',
Expand Down