Browse Source

ref(ui): Remove createReactClass from withProjectsSpecified (#26524)

Matej Minar 3 years ago
parent
commit
7b31a1c83e
1 changed files with 30 additions and 23 deletions
  1. 30 23
      static/app/utils/withProjectsSpecified.tsx

+ 30 - 23
static/app/utils/withProjectsSpecified.tsx

@@ -1,7 +1,5 @@
 import * as React from 'react';
-import createReactClass from 'create-react-class';
-import xor from 'lodash/xor';
-import Reflux from 'reflux';
+import isEqual from 'lodash/isEqual';
 
 import ProjectsStore from 'app/stores/projectsStore';
 import {Project} from 'app/types';
@@ -24,27 +22,33 @@ type State = {
 /**
  * Higher order component that takes specificProjectSlugs and provides list of that projects from ProjectsStore
  */
-const withProjectsSpecified = <P extends InjectedProjectsProps>(
+function withProjectsSpecified<P extends InjectedProjectsProps>(
   WrappedComponent: React.ComponentType<P>
-) =>
-  createReactClass<Props & Omit<P, keyof InjectedProjectsProps>, State>({
-    displayName: `withProjectsSpecified(${getDisplayName(WrappedComponent)})`,
-    mixins: [Reflux.listenTo(ProjectsStore, 'onProjectUpdate') as any],
-    getInitialState() {
-      return ProjectsStore.getState(this.props.specificProjectSlugs);
-    },
-
-    UNSAFE_componentWillReceiveProps(nextProps: Props) {
-      const {specificProjectSlugs} = this.props;
-
-      if (xor(nextProps.specificProjectSlugs, specificProjectSlugs).length) {
-        this.setState(ProjectsStore.getState(nextProps.specificProjectSlugs));
+) {
+  class WithProjectsSpecified extends React.Component<
+    Props & Omit<P, keyof InjectedProjectsProps>,
+    State
+  > {
+    static displayName = `withProjectsSpecified(${getDisplayName(WrappedComponent)})`;
+
+    state = ProjectsStore.getState(this.props.specificProjectSlugs);
+
+    static getDerivedStateFromProps(nextProps: Readonly<Props>): State {
+      return ProjectsStore.getState(nextProps.specificProjectSlugs);
+    }
+
+    componentWillUnmount() {
+      this.unsubscribe();
+    }
+
+    unsubscribe = ProjectsStore.listen(() => {
+      const storeState = ProjectsStore.getState(this.props.specificProjectSlugs);
+
+      if (!isEqual(this.state, storeState)) {
+        this.setState(storeState);
       }
-    },
+    }, undefined);
 
-    onProjectUpdate() {
-      this.setState(ProjectsStore.getState(this.props.specificProjectSlugs));
-    },
     render() {
       return (
         <WrappedComponent
@@ -53,7 +57,10 @@ const withProjectsSpecified = <P extends InjectedProjectsProps>(
           loadingProjects={this.state.loading}
         />
       );
-    },
-  });
+    }
+  }
+
+  return WithProjectsSpecified;
+}
 
 export default withProjectsSpecified;