no-set-state.js 2.4 KB

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