withConfig.tsx 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import React from 'react';
  2. import createReactClass from 'create-react-class';
  3. import Reflux from 'reflux';
  4. import ConfigStore from 'app/stores/configStore';
  5. import {Config} from 'app/types';
  6. import getDisplayName from 'app/utils/getDisplayName';
  7. type InjectedConfigProps = {
  8. config: Config;
  9. };
  10. type State = {
  11. config: Config;
  12. };
  13. /**
  14. * Higher order component that passes the config object to the wrapped component
  15. */
  16. const withConfig = <P extends InjectedConfigProps>(
  17. WrappedComponent: React.ComponentType<P>
  18. ) =>
  19. createReactClass<
  20. Omit<P, keyof InjectedConfigProps> & Partial<InjectedConfigProps>,
  21. State
  22. >({
  23. displayName: `withConfig(${getDisplayName(WrappedComponent)})`,
  24. mixins: [Reflux.listenTo(ConfigStore, 'onUpdate') as any],
  25. getInitialState() {
  26. return {config: ConfigStore.getConfig()};
  27. },
  28. onUpdate() {
  29. this.setState({config: ConfigStore.getConfig()});
  30. },
  31. render() {
  32. const {config, ...props} = this.props as P;
  33. return (
  34. <WrappedComponent {...({config: config ?? this.state.config, ...props} as P)} />
  35. );
  36. },
  37. });
  38. export default withConfig;