1import React, { useContext, useEffect, useMemo, useState } from "react";
2import { storeContext } from "./context";
3
4export const ConnectComponent = (props: any) => {
5 const {
6 WrapperComponent,
7 mapStateToProps,
8 mapDispatchToProps,
9 ...restProps
10 } = props;
11 const [, forceUpdate] = useState<any>();
12 const { dispatch, getState, subscribe } = useContext(storeContext);
13 const state = getState();
14
15 const mapState = useMemo(() => {
16 if (!mapStateToProps) {
17 return state;
18 }
19 return mapStateToProps(state);
20 }, [state]);
21
22 const mapAction = useMemo(() => {
23 if (!mapDispatchToProps) {
24 return {};
25 }
26 return mapDispatchToProps(dispatch);
27 }, [dispatch]);
28
29 const memoComponent = useMemo(() => {
30 return (
31 <WrapperComponent
32 {...mapState}
33 {...mapAction}
34 {...restProps}
35 dispatch={dispatch}
36 />
37 );
38 }, [mapState, mapAction]);
39
40 const unsubscribe = subscribe(() => {
41 forceUpdate({});
42 });
43
44 return memoComponent;
45};
46
47export const connect = (mapStateToProps?: any, mapDispatchToProps?: any) => {
48 return (WrapperComponent: React.ElementType) => (props: any) => (
49 <ConnectComponent
50 {...props}
51 mapStateToProps={mapStateToProps}
52 WrapperComponent={WrapperComponent}
53 mapDispatchToProps={mapDispatchToProps}
54 />
55 );
56};