no-set-state.js 2.4 KB

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