Skip to content

Commit 2f06677

Browse files
committed
Add option for state-in-constructor rule
1 parent a312b16 commit 2f06677

File tree

2 files changed

+297
-16
lines changed

2 files changed

+297
-16
lines changed

lib/rules/state-in-constructor.js

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* @fileoverview State initialization in an ES6 class component should be in a constructor
2+
* @fileoverview Enforce the state initialization style to be either in a constructor or with a class property
33
* @author Kanitkorn Sujautra
44
*/
55
'use strict';
@@ -19,21 +19,41 @@ module.exports = {
1919
recommended: false,
2020
url: docsUrl('state-in-constructor')
2121
},
22-
schema: []
22+
schema: [{
23+
enum: ['always', 'never']
24+
}]
2325
},
2426

25-
create: Components.detect((context, components, utils) => ({
26-
ClassProperty: function (node) {
27-
if (
28-
!node.static &&
29-
node.key.name === 'state' &&
30-
utils.isES6Component(node.parent.parent)
31-
) {
32-
context.report({
33-
node,
34-
message: 'State initialization should be in a constructor'
35-
});
27+
create: Components.detect((context, components, utils) => {
28+
const option = context.options[0] || 'always';
29+
return {
30+
ClassProperty: function (node) {
31+
if (
32+
option === 'always' &&
33+
!node.static &&
34+
node.key.name === 'state' &&
35+
utils.isES6Component(node.parent.parent)
36+
) {
37+
context.report({
38+
node,
39+
message: 'State initialization should be in a constructor'
40+
});
41+
}
42+
},
43+
AssignmentExpression(node) {
44+
if (
45+
option === 'never' &&
46+
node.left.object.type === 'ThisExpression' &&
47+
node.left.property.name === 'state' &&
48+
node.parent.parent.parent.parent.kind === 'constructor' &&
49+
utils.isES6Component(node.parent.parent.parent.parent.parent.parent)
50+
) {
51+
context.report({
52+
node,
53+
message: 'State initialization should be in a class property'
54+
});
55+
}
3656
}
37-
}
38-
}))
57+
};
58+
})
3959
};

0 commit comments

Comments
 (0)