redoc/src/components/StoreProvider.ts

94 lines
2.1 KiB
TypeScript
Raw Normal View History

import memoize from 'memoize-one';
import { Component } from 'react';
import { AppStore } from '../services/';
2017-11-21 14:00:33 +03:00
import { RedocRawOptions } from '../services/RedocNormalizedOptions';
2018-03-13 14:04:55 +03:00
import { loadAndBundleSpec } from '../utils';
2017-10-12 00:01:37 +03:00
2018-05-16 12:44:36 +03:00
export 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;
onLoaded?: (e?: Error) => void;
children: (props: { loading: boolean; store?: AppStore }) => any;
2017-10-12 00:01:37 +03:00
}
2018-05-16 12:44:36 +03:00
export interface StoreProviderState {
error?: Error;
loading: boolean;
resolvedSpec?: any;
prevSpec?: any;
prevSpecUrl?: string;
}
2017-10-12 00:01:37 +03:00
export class StoreProvider extends Component<StoreProviderProps, StoreProviderState> {
static getDerivedStateFromProps(nextProps: StoreProviderProps, prevState: StoreProviderState) {
if (nextProps.specUrl !== prevState.prevSpecUrl || nextProps.spec !== prevState.prevSpec) {
return {
loading: true,
resolvedSpec: null,
prevSpec: nextProps.spec,
prevSpecUrl: nextProps.specUrl,
};
}
2017-10-12 00:01:37 +03:00
return null;
}
state: StoreProviderState = {
loading: true,
resolvedSpec: null,
};
@memoize
makeStore(spec, specUrl, options) {
if (!spec) {
return undefined;
}
return new AppStore(spec, specUrl, options);
2017-11-20 02:00:43 +03:00
}
2017-11-20 02:00:43 +03:00
componentDidMount() {
this.load();
}
componentDidUpdate() {
if (this.state.resolvedSpec === null) {
this.load();
} else if (!this.state.loading && this.props.onLoaded) {
// may run multiple time
this.props.onLoaded();
}
}
async load() {
const { specUrl, spec, options } = this.props;
try {
const resolvedSpec = await loadAndBundleSpec(spec || specUrl!);
this.setState({ resolvedSpec, loading: false });
} catch (e) {
if (this.props.onLoaded) {
this.props.onLoaded(e);
}
this.setState({ error: e });
}
}
2017-10-12 00:01:37 +03:00
render() {
2018-01-22 21:30:53 +03:00
if (this.state.error) {
throw this.state.error;
}
const { specUrl, options } = this.props;
const { loading, resolvedSpec } = this.state;
return this.props.children({
loading,
store: this.makeStore(resolvedSpec, specUrl, options),
});
2017-10-12 00:01:37 +03:00
}
}