grafana/public/app/core/components/connectWithCleanUp.tsx
Hugo Häggmark 133ddc9afb
Feature: Adds connectWithCleanup HOC (#19629)
* Feature: Adds connectWithCleanup HOC

* Refactor: Small typings

* Refactor: Makes UseEffect run on Mount and UnMount only

* Refactor: Adds tests and rootReducer

* Refactor: Fixes adding of reducers on startup
2019-10-08 21:37:07 -07:00

40 lines
1.4 KiB
TypeScript

import { MapStateToPropsParam, MapDispatchToPropsParam, connect, useDispatch } from 'react-redux';
import { StateSelector, cleanUpAction } from '../actions/cleanUp';
import React, { ComponentType, FunctionComponent, useEffect } from 'react';
import hoistNonReactStatics from 'hoist-non-react-statics';
export const connectWithCleanUp = <
TStateProps extends {} = {},
TDispatchProps = {},
TOwnProps = {},
State = {},
TSelector extends object = {},
Statics = {}
>(
mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
mapDispatchToProps: MapDispatchToPropsParam<TDispatchProps, TOwnProps>,
stateSelector: StateSelector<TSelector>
) => (Component: ComponentType<any>) => {
const ConnectedComponent = connect(
mapStateToProps,
mapDispatchToProps
)(Component);
const ConnectedComponentWithCleanUp: FunctionComponent = props => {
const dispatch = useDispatch();
useEffect(() => {
return function cleanUp() {
dispatch(cleanUpAction({ stateSelector }));
};
}, []);
// @ts-ignore
return <ConnectedComponent {...props} />;
};
ConnectedComponentWithCleanUp.displayName = `ConnectWithCleanUp(${ConnectedComponent.displayName})`;
hoistNonReactStatics(ConnectedComponentWithCleanUp, Component);
type Hoisted = typeof ConnectedComponentWithCleanUp & Statics;
return ConnectedComponentWithCleanUp as Hoisted;
};