Skip to content

Commit

Permalink
Merge 6697a04 into 8f8e7c1
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitormdias committed Apr 12, 2019
2 parents 8f8e7c1 + 6697a04 commit 355475f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 58 deletions.
12 changes: 1 addition & 11 deletions lib/interfaces/plug.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,3 @@
import { Observable } from "rxjs";

export type TStream = (stream: any) => Observable<any>;

export interface ILifecycle {
componentDidMount: () => void;
componentWillUnmount: () => void;
}

export interface IPlugState {
hasEmmited: boolean;
innerData?: any;
}
export type TStream = (stream: any) => Observable<any>;
69 changes: 22 additions & 47 deletions lib/plug.tsx
Original file line number Diff line number Diff line change
@@ -1,51 +1,26 @@
import * as React from 'react';
import { Component } from 'react';
import { Subscription } from 'rxjs';
import { TStream, ILifecycle, IPlugState } from './interfaces/plug';


export const plug = <T extends {}>(stream: TStream, lifecycleHooks: Partial<ILifecycle> = {},
) => (WrappedComponent: any) =>
class PluggedComponent extends Component<T, IPlugState> {

_streamSubscription!: Subscription;

constructor(props: any) {
super(props);

this.state = {
hasEmmited: false,
};
}

public componentDidMount() {
this._streamSubscription = stream(this.props).subscribe((data: any) =>
this.setState({
hasEmmited: true,
innerData: data,
}),
);

if (lifecycleHooks.componentDidMount) {
lifecycleHooks.componentDidMount();
}
}

public componentWillUnmount() {
this._streamSubscription.unsubscribe();

if (lifecycleHooks.componentWillUnmount) {
lifecycleHooks.componentWillUnmount();
}
import { useState, useEffect } from 'react';
import { TStream } from './interfaces/plug';

export const plug = <T extends {}>(stream: TStream) => (WrappedComponent: any) => (props: T) => {
const [hasEmmited, setHasEmitted] = useState(false);
const [innerData, setInnerData] = useState({});

useEffect(() => {
const streamSubscription = stream(props)
.subscribe((data: any) => {
setHasEmitted(true);
setInnerData(data);
});

return () => {
streamSubscription.unsubscribe();
}
}, [])

public render() {
const { hasEmmited, innerData } = this.state;

if (hasEmmited) {
return <WrappedComponent {...innerData} />;
}
if (hasEmmited) {
return <WrappedComponent {...innerData} />;
}

return null;
}
}
return null;
}

0 comments on commit 355475f

Please sign in to comment.