forked from jsx-eslint/eslint-plugin-react
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmakeNoMethodSetStateRule.js
70 lines (60 loc) · 1.92 KB
/
makeNoMethodSetStateRule.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* @fileoverview Prevent usage of setState in lifecycle methods
* @author Yannick Croissant
*/
'use strict';
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
function makeNoMethodSetStateRule(methodName) {
return {
meta: {
docs: {
description: 'Prevent usage of setState in ' + methodName,
category: 'Best Practices',
recommended: false
},
schema: [{
enum: ['disallow-in-func']
}]
},
create: function(context) {
var mode = context.options[0] || 'allow-in-func';
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
CallExpression: function(node) {
var callee = node.callee;
if (
callee.type !== 'MemberExpression' ||
callee.object.type !== 'ThisExpression' ||
callee.property.name !== 'setState'
) {
return;
}
var ancestors = context.getAncestors(callee).reverse();
var depth = 0;
for (var i = 0, j = ancestors.length; i < j; i++) {
if (/Function(Expression|Declaration)$/.test(ancestors[i].type)) {
depth++;
}
if (
(ancestors[i].type !== 'Property' && ancestors[i].type !== 'MethodDefinition') ||
ancestors[i].key.name !== methodName ||
(mode !== 'disallow-in-func' && depth > 1)
) {
continue;
}
context.report({
node: callee,
message: 'Do not use setState in ' + methodName
});
break;
}
}
};
}
};
}
module.exports = makeNoMethodSetStateRule;