|
@@ -1,7 +1,6 @@
|
|
|
-import * as React from 'react';
|
|
|
-
|
|
|
import {Client} from 'app/api';
|
|
|
import getDisplayName from 'app/utils/getDisplayName';
|
|
|
+import useApi from 'app/utils/useApi';
|
|
|
|
|
|
type InjectedApiProps = {
|
|
|
api: Client;
|
|
@@ -9,46 +8,26 @@ type InjectedApiProps = {
|
|
|
|
|
|
type WrappedProps<P> = Omit<P, keyof InjectedApiProps> & Partial<InjectedApiProps>;
|
|
|
|
|
|
-type OptionProps = {
|
|
|
- /**
|
|
|
- * Enabling this option will disable clearing in-flight requests when the
|
|
|
- * component is unmounted.
|
|
|
- *
|
|
|
- * This may be useful in situations where your component needs to finish up
|
|
|
- * some where the client was passed into some type of action creator and the
|
|
|
- * component is unmounted.
|
|
|
- */
|
|
|
- persistInFlight?: boolean;
|
|
|
-};
|
|
|
-
|
|
|
/**
|
|
|
* React Higher-Order Component (HoC) that provides "api" client when mounted,
|
|
|
* and clears API requests when component is unmounted.
|
|
|
+ *
|
|
|
+ * If an `api` prop is provided when the component is invoked it will be passed
|
|
|
+ * through.
|
|
|
*/
|
|
|
const withApi = <P extends InjectedApiProps>(
|
|
|
WrappedComponent: React.ComponentType<P>,
|
|
|
- {persistInFlight}: OptionProps = {}
|
|
|
-) =>
|
|
|
- class extends React.Component<WrappedProps<P>> {
|
|
|
- static displayName = `withApi(${getDisplayName(WrappedComponent)})`;
|
|
|
-
|
|
|
- constructor(props: WrappedProps<P>) {
|
|
|
- super(props);
|
|
|
- this.api = new Client();
|
|
|
- }
|
|
|
+ options: Parameters<typeof useApi>[0] = {}
|
|
|
+) => {
|
|
|
+ const WithApi: React.FC<WrappedProps<P>> = ({api: propsApi, ...props}) => {
|
|
|
+ const api = useApi({api: propsApi, ...options});
|
|
|
|
|
|
- componentWillUnmount() {
|
|
|
- if (!persistInFlight) {
|
|
|
- this.api.clear();
|
|
|
- }
|
|
|
- }
|
|
|
+ return <WrappedComponent {...(props as P)} api={api} />;
|
|
|
+ };
|
|
|
|
|
|
- private api: Client;
|
|
|
+ WithApi.displayName = `withApi(${getDisplayName(WrappedComponent)})`;
|
|
|
|
|
|
- render() {
|
|
|
- const {api, ...props} = this.props;
|
|
|
- return <WrappedComponent {...({api: api ?? this.api, ...props} as P)} />;
|
|
|
- }
|
|
|
- };
|
|
|
+ return WithApi;
|
|
|
+};
|
|
|
|
|
|
export default withApi;
|