-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathwith-connected-count.tsx
60 lines (51 loc) · 1.67 KB
/
with-connected-count.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { RootState } from 'MyTypes';
import React from 'react';
import { connect } from 'react-redux';
import { Diff } from 'utility-types';
import { countersActions, countersSelectors } from '../features/counters';
// These props will be injected into the base component
interface InjectedProps {
count: number;
onIncrement: () => void;
}
export const withConnectedCount = <BaseProps extends InjectedProps>(
BaseComponent: React.ComponentType<BaseProps>
) => {
const mapStateToProps = (state: RootState) => ({
count: countersSelectors.getReduxCounter(state.counters),
});
const dispatchProps = {
onIncrement: countersActions.increment,
};
type HocProps = ReturnType<typeof mapStateToProps> &
typeof dispatchProps & {
// here you can extend ConnectedHoc with new props
overrideCount?: number;
};
class Hoc extends React.Component<HocProps> {
// Enhance component name for debugging and React-Dev-Tools
static displayName = `withConnectedCount(${BaseComponent.name})`;
// reference to original wrapped component
static readonly WrappedComponent = BaseComponent;
render() {
const { count, onIncrement, overrideCount, ...restProps } = this.props;
return (
<BaseComponent
{...(restProps as BaseProps)}
count={overrideCount || count} // injected
onIncrement={onIncrement} // injected
/>
);
}
}
const ConnectedHoc = connect<
ReturnType<typeof mapStateToProps>,
typeof dispatchProps, // use "undefined" if NOT using dispatchProps
Diff<BaseProps, InjectedProps>,
RootState
>(
mapStateToProps,
dispatchProps
)(Hoc);
return ConnectedHoc;
};