mirror of
https://github.com/grafana/grafana.git
synced 2025-02-15 10:03:33 -06:00
* 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
40 lines
1.4 KiB
TypeScript
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;
|
|
};
|