redoc/src/components/StoreProvider.ts

69 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Component } from 'react';
import { AppStore } from '../services/';
import { loadAndBundleSpec } from '../utils';
2017-11-21 14:00:33 +03:00
import { RedocRawOptions } from '../services/RedocNormalizedOptions';
2017-10-12 00:01:37 +03:00
interface StoreProviderProps {
2017-10-12 00:01:37 +03:00
specUrl?: string;
spec?: object;
store?: AppStore;
2017-11-21 14:00:33 +03:00
options?: RedocRawOptions;
children: (props: { loading: boolean; store?: AppStore }) => any;
2017-10-12 00:01:37 +03:00
}
interface StoreProviderState {
error?: Error;
loading: boolean;
store?: AppStore;
}
2017-10-12 00:01:37 +03:00
export class StoreProvider extends Component<StoreProviderProps, StoreProviderState> {
store: AppStore;
2017-10-12 00:01:37 +03:00
constructor(props: StoreProviderProps) {
2017-10-12 00:01:37 +03:00
super(props);
this.state = {
loading: true,
};
2017-11-20 02:00:43 +03:00
}
2017-11-20 02:00:43 +03:00
componentDidMount() {
this.load();
}
async load() {
2017-11-21 14:00:33 +03:00
let { specUrl, spec, options } = this.props;
this.setState({
loading: true,
});
try {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl!);
this.setState({
loading: false,
2017-11-21 14:00:33 +03:00
store: new AppStore(resolvedSpec, specUrl, options),
});
} catch (e) {
this.setState({
error: e,
});
2017-10-12 00:01:37 +03:00
}
}
setError(e?: Error) {
this.setState({
error: e,
});
}
render() {
if (this.state.error) throw this.state.error;
return this.props.children(this.state);
2017-10-12 00:01:37 +03:00
}
}