grafana/public/app/core/components/connectWithCleanUp.tsx
Hugo Häggmark e4c33e0be8
Chore: Updates yarn.lock (#19919)
* Chore: Updates yarn.lock

* Chore: Fixes @types/webpack conflict
2019-10-19 09:30:12 +02:00

41 lines
1.4 KiB
TypeScript

import { connect, MapDispatchToPropsParam, MapStateToPropsParam, useDispatch } from 'react-redux';
import { cleanUpAction, StateSelector } 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
// @ts-ignore
)(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;
};