/
connect.js
57 lines (47 loc) · 1.52 KB
/
connect.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
import React, { Component } from 'react';
import shallowCompare from 'react-addons-shallow-compare';
import storeShape from './storeShape';
const getDisplayName = WrappedComponent =>
WrappedComponent.displayName || WrappedComponent.name || 'UnknownComponent';
export default function connect(mapStateToProps) {
return WrappedComponent =>
class Connect extends Component {
static contextTypes = { algoliaStore: storeShape.isRequired };
static displayName = `AlgoliaSearchHelperConnect(${getDisplayName(
WrappedComponent
)})`;
constructor(props, context) {
super();
if (mapStateToProps) {
this.state = mapStateToProps(context.algoliaStore.getState(), props);
this.unsubscribe = context.algoliaStore.subscribe(() => {
this.setState(
mapStateToProps(context.algoliaStore.getState(), this.props)
);
});
}
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
componentWillReceiveProps(nextProps) {
this.setState(
mapStateToProps(this.context.algoliaStore.getState(), nextProps)
);
}
shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
render() {
return (
<WrappedComponent
{...this.props}
{...this.state}
helper={this.context.algoliaStore.getHelper()}
/>
);
}
};
}