Total Complexity | 5 |
Complexity/F | 1.25 |
Lines of Code | 51 |
Function Count | 4 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
1 | /* eslint-disable @typescript-eslint/ban-ts-comment */ |
||
2 | import React from "react"; |
||
3 | |||
4 | interface Props<P> { |
||
5 | [key: string]: any; |
||
6 | } |
||
7 | |||
8 | /** |
||
9 | * This is a HOC (Higher Order Component). |
||
10 | * It can be used to log which properties of a component changed when it re-rerenders. |
||
11 | * Use it by wrapping the exported component function, similarly to connect() or injectIntl(). |
||
12 | * For Debugging use only. |
||
13 | * @param WrappedComponent |
||
14 | */ |
||
15 | export default function withPropsChecker<P>( |
||
16 | WrappedComponent: React.ComponentType<P>, |
||
17 | ): React.ComponentClass<Props<P>> { |
||
18 | return class PropsChecker extends React.Component<Props<P>> { |
||
19 | // eslint-disable-next-line camelcase |
||
20 | public UNSAFE_componentWillReceiveProps(nextProps: Props<P>): void { |
||
21 | if (process.env.NODE_ENV === "development") { |
||
22 | this.logChanges(nextProps); |
||
23 | } |
||
24 | } |
||
25 | |||
26 | private logChanges(nextProps: Props<P>): void { |
||
27 | Object.keys(nextProps) |
||
28 | // eslint-disable-next-line react/destructuring-assignment |
||
29 | .filter((key): boolean => nextProps[key] !== this.props[key]) |
||
30 | .forEach((key): void => { |
||
31 | // eslint-disable-next-line no-console |
||
32 | console.log( |
||
33 | WrappedComponent.name, |
||
34 | "changed property:", |
||
35 | key, |
||
36 | "from", |
||
37 | // eslint-disable-next-line react/destructuring-assignment |
||
38 | this.props[key], |
||
39 | "to", |
||
40 | nextProps[key], |
||
41 | ); |
||
42 | }); |
||
43 | } |
||
44 | |||
45 | public render(): React.ReactElement { |
||
46 | // @ts-ignore |
||
47 | return <WrappedComponent {...this.props} />; |
||
48 | } |
||
49 | }; |
||
50 | } |
||
51 |