ObservablePropsWrapper.tsx 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import React, { Component } from 'react';
  2. import { Observable, Unsubscribable } from 'rxjs';
  3. interface Props<T> {
  4. watch: Observable<T>;
  5. child: React.ComponentType<T>;
  6. initialSubProps: T;
  7. }
  8. interface State<T> {
  9. subProps: T;
  10. }
  11. export class ObservablePropsWrapper<T> extends Component<Props<T>, State<T>> {
  12. sub?: Unsubscribable;
  13. constructor(props: Props<T>) {
  14. super(props);
  15. this.state = {
  16. subProps: props.initialSubProps,
  17. };
  18. }
  19. componentDidMount() {
  20. this.sub = this.props.watch.subscribe({
  21. next: (subProps: T) => {
  22. //console.log('ObservablePropsWrapper:NEXT', subProps);
  23. this.setState({ subProps });
  24. },
  25. complete: () => {
  26. //console.log('ObservablePropsWrapper:complete');
  27. },
  28. error: (err) => {
  29. //console.log('ObservablePropsWrapper:error', err);
  30. },
  31. });
  32. }
  33. componentWillUnmount() {
  34. if (this.sub) {
  35. this.sub.unsubscribe();
  36. }
  37. }
  38. render() {
  39. const { subProps } = this.state;
  40. return <this.props.child {...subProps} />;
  41. }
  42. }