-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwithHiveSubscription.tsx
80 lines (60 loc) · 2.07 KB
/
withHiveSubscription.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* A High Order Component that injects the modified hive data and service as properties.
Also, registers for changes in data from hive so component will re-render when updates are
pulled from hive
*/
import * as React from 'react';
import hoistNonReactStatic from 'hoist-non-react-statics';
import HiveService from './hive.service';
import { INode, ValueType, IHiveValueSet } from './hive-interfaces';
export interface HiveSubscriptionProps {
}
export interface IHiveSubscriptionState {
hive: HiveService;
sessionId?: string;
nodes: INode[];
[index: string] : IHiveValueSet | undefined | any
}
function enhance(WrappedComponent: React.ComponentClass<any>, hiveService: HiveService) {
class HiveSubscription extends React.Component<HiveSubscriptionProps, IHiveSubscriptionState> {
constructor(props: HiveSubscriptionProps) {
super(props);
this.state = {
hive: hiveService,
nodes: [],
values: {} as any
} as IHiveSubscriptionState;
this.displayName = `HiveSubscription(${this.getDisplayName(WrappedComponent)})`;
this.onDataChange = this.onDataChange.bind(this);
}
displayName : string;
public render() {
return <WrappedComponent {...this.state} {...this.props}/>;
}
getDisplayName(component: React.ComponentClass) {
return component.displayName || component.name || 'Component';
}
onDataChange(data : any) {
this.setState(data);
}
componentDidMount() {
const { hive } = this.state;
hive.registerChangeHandler(this.onDataChange);
}
componentWillUnmount() {
const { hive } = this.state;
hive.unRegisterChangeHandler(this.onDataChange);
}
};
hoistNonReactStatic(HiveSubscription, WrappedComponent);
return HiveSubscription;
}
let serviceSingleton: HiveService;
export default function withHiveSubscription() {
let service = serviceSingleton;
if(!service) {
service = serviceSingleton = new HiveService();
}
return (wrappedComponent: React.ComponentClass<any,any>) => {
return enhance(wrappedComponent, service);
}
}