forked from gaearon/react-side-effect
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
68 lines (55 loc) · 1.69 KB
/
index.js
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
61
62
63
64
65
66
67
68
import React, {PureComponent} from 'react';
export default function withSideEffect(
reducePropsToState,
handleStateChangeOnClient
) {
if (process.env.NODE_ENV !== "production") {
if (typeof reducePropsToState !== 'function') {
throw new Error('Expected reducePropsToState to be a function.');
}
if (typeof handleStateChangeOnClient !== 'function') {
throw new Error('Expected handleStateChangeOnClient to be a function.');
}
}
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
return function wrap(WrappedComponent) {
if (process.env.NODE_ENV !== "production") {
if (typeof WrappedComponent !== 'function') {
throw new Error('Expected WrappedComponent to be a React component.');
}
}
let mountedInstances = [];
let state;
function emitChange() {
state = reducePropsToState(mountedInstances.map(function (instance) {
return instance.props;
}));
handleStateChangeOnClient(state);
}
class SideEffect extends PureComponent {
// Try to use displayName of wrapped component
static displayName = `SideEffect(${getDisplayName(WrappedComponent)})`;
static peek() {
return state;
}
componentDidMount() {
mountedInstances.push(this);
emitChange();
}
componentDidUpdate() {
emitChange();
}
componentWillUnmount() {
const index = mountedInstances.indexOf(this);
mountedInstances.splice(index, 1);
emitChange();
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return SideEffect;
}
}