source: imaps-frontend/node_modules/eslint-plugin-react/lib/rules/no-set-state.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 2.3 KB
Line 
1/**
2 * @fileoverview Prevent usage of setState
3 * @author Mark Dalgleish
4 */
5
6'use strict';
7
8const values = require('object.values');
9
10const Components = require('../util/Components');
11const docsUrl = require('../util/docsUrl');
12const report = require('../util/report');
13
14// ------------------------------------------------------------------------------
15// Rule Definition
16// ------------------------------------------------------------------------------
17
18const messages = {
19 noSetState: 'Do not use setState',
20};
21
22/** @type {import('eslint').Rule.RuleModule} */
23module.exports = {
24 meta: {
25 docs: {
26 description: 'Disallow usage of setState',
27 category: 'Stylistic Issues',
28 recommended: false,
29 url: docsUrl('no-set-state'),
30 },
31
32 messages,
33
34 schema: [],
35 },
36
37 create: Components.detect((context, components, utils) => {
38 /**
39 * Checks if the component is valid
40 * @param {Object} component The component to process
41 * @returns {Boolean} True if the component is valid, false if not.
42 */
43 function isValid(component) {
44 return Boolean(component && !component.useSetState);
45 }
46
47 /**
48 * Reports usages of setState for a given component
49 * @param {Object} component The component to process
50 */
51 function reportSetStateUsages(component) {
52 let setStateUsage;
53 for (let i = 0, j = component.setStateUsages.length; i < j; i++) {
54 setStateUsage = component.setStateUsages[i];
55 report(context, messages.noSetState, 'noSetState', {
56 node: setStateUsage,
57 });
58 }
59 }
60
61 return {
62 CallExpression(node) {
63 const callee = node.callee;
64 if (
65 callee.type !== 'MemberExpression'
66 || callee.object.type !== 'ThisExpression'
67 || callee.property.name !== 'setState'
68 ) {
69 return;
70 }
71 const component = components.get(utils.getParentComponent(node));
72 const setStateUsages = (component && component.setStateUsages) || [];
73 setStateUsages.push(callee);
74 components.set(node, {
75 useSetState: true,
76 setStateUsages,
77 });
78 },
79
80 'Program:exit'() {
81 values(components.list())
82 .filter((component) => !isValid(component))
83 .forEach((component) => {
84 reportSetStateUsages(component);
85 });
86 },
87 };
88 }),
89};
Note: See TracBrowser for help on using the repository browser.