zepio/app/components/with-daemon-status-check.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2018-12-11 04:13:45 -08:00
// @flow
2019-02-04 20:41:45 -08:00
2018-12-11 04:13:45 -08:00
import React, { type ComponentType, Component } from 'react';
import { LoadingScreen } from './loading-screen';
2018-12-11 04:13:45 -08:00
import rpc from '../../services/api';
type Props = {};
2018-12-11 04:13:45 -08:00
type State = {
isRunning: boolean,
progress: number,
2018-12-11 04:13:45 -08:00
};
2018-12-15 07:10:39 -08:00
/* eslint-disable max-len */
2018-12-11 04:13:45 -08:00
export const withDaemonStatusCheck = <PassedProps: {}>(
WrappedComponent: ComponentType<PassedProps>,
): ComponentType<$Diff<PassedProps, Props>> => class extends Component<PassedProps, State> {
timer: ?IntervalID = null;
state = {
isRunning: false,
progress: 0,
2018-12-11 04:13:45 -08:00
};
componentDidMount() {
this.runTest();
this.timer = setInterval(this.runTest, 2000);
2018-12-11 04:13:45 -08:00
}
componentWillUnmount() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
runTest = () => {
rpc
.getinfo()
.then((response) => {
if (response) {
setTimeout(() => {
this.setState(() => ({ isRunning: true }));
}, 500);
this.setState(() => ({ progress: 100 }));
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
})
.catch(() => {
this.setState((state) => {
const newProgress = state.progress > 70 ? state.progress + 2.5 : state.progress + 5;
return { progress: newProgress > 95 ? 95 : newProgress };
});
});
};
2018-12-11 04:13:45 -08:00
render() {
const { isRunning, progress } = this.state;
if (isRunning) {
2018-12-11 04:13:45 -08:00
return <WrappedComponent {...this.props} {...this.state} />;
}
return <LoadingScreen progress={progress} />;
2018-12-11 04:13:45 -08:00
}
};