-
Notifications
You must be signed in to change notification settings - Fork 0
/
withServices.js
45 lines (41 loc) · 1.18 KB
/
withServices.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
import React from 'react';
import {start} from 'ineedthis';
export default function withServices(
servicesMap,
{loadingProp='isLoading', delayRender=false} = {}
) {
return WrappedComponent => {
return class extends React.Component {
constructor() {
super();
const childProps = {};
for (const k of Object.keys(servicesMap)) {
childProps[k] = null;
}
childProps[loadingProp] = true;
this.state = {childProps};
}
async componentWillMount() {
let sys;
try {
sys = await start(Object.values(servicesMap));
} catch (e) {
console.error('WTF couldn\'t start services', e);
return;
}
const newChildProps = {};
for (const [prop, s] of Object.entries(servicesMap)) {
newChildProps[prop] = sys[s.serviceName];
}
newChildProps[loadingProp] = false;
this.setState(() => ({childProps: newChildProps}));
}
render() {
if (delayRender && this.state.childProps[loadingProp]) {
return null;
}
return <WrappedComponent {...this.props} {...this.state.childProps}/>
}
};
};
}