From b086a7a28a62f0708c8dd93fbe1eea153a4c9657 Mon Sep 17 00:00:00 2001 From: vitormanfre Date: Fri, 12 Apr 2019 09:47:14 -0300 Subject: [PATCH 1/2] removes unecessary interfaces --- lib/interfaces/plug.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/lib/interfaces/plug.ts b/lib/interfaces/plug.ts index e1b3b23..31793f7 100644 --- a/lib/interfaces/plug.ts +++ b/lib/interfaces/plug.ts @@ -1,13 +1,3 @@ import { Observable } from "rxjs"; -export type TStream = (stream: any) => Observable; - -export interface ILifecycle { - componentDidMount: () => void; - componentWillUnmount: () => void; -} - -export interface IPlugState { - hasEmmited: boolean; - innerData?: any; -} \ No newline at end of file +export type TStream = (stream: any) => Observable; \ No newline at end of file From 6697a040c31e3c798144fb9f1ea2ebf6d959cf45 Mon Sep 17 00:00:00 2001 From: vitormanfre Date: Fri, 12 Apr 2019 09:47:55 -0300 Subject: [PATCH 2/2] refactor plug HOC to use react hooks --- lib/plug.tsx | 69 +++++++++++++++++----------------------------------- 1 file changed, 22 insertions(+), 47 deletions(-) diff --git a/lib/plug.tsx b/lib/plug.tsx index 25c6a0e..5f3506b 100644 --- a/lib/plug.tsx +++ b/lib/plug.tsx @@ -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 = (stream: TStream, lifecycleHooks: Partial = {}, -) => (WrappedComponent: any) => - class PluggedComponent extends Component { - - _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 = (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 ; - } + if (hasEmmited) { + return ; + } - return null; - } - } \ No newline at end of file + return null; +}