kibana/x-pack/plugins/spaces/public/ui_api/lazy_wrapper.tsx
Joe Portner f61d1d306d
[7.x] Cleanup spaces plugin (#91976) (#93032)
* Cleanup spaces plugin (#91976)

# Conflicts:
#	x-pack/plugins/security/public/management/roles/roles_management_app.tsx

* Make the linter happy

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
2021-03-01 13:57:56 -05:00

42 lines
1.3 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type { FC, PropsWithChildren, PropsWithRef, ReactElement } from 'react';
import React, { lazy, useMemo } from 'react';
import useAsync from 'react-use/lib/useAsync';
import type { StartServicesAccessor } from 'src/core/public';
import type { PluginsStart } from '../plugin';
import { SuspenseErrorBoundary } from '../suspense_error_boundary';
interface InternalProps<T> {
fn: () => Promise<FC<T>>;
getStartServices: StartServicesAccessor<PluginsStart>;
props: JSX.IntrinsicAttributes & PropsWithRef<PropsWithChildren<T>>;
}
export const LazyWrapper: <T>(props: InternalProps<T>) => ReactElement | null = ({
fn,
getStartServices,
props,
}) => {
const { value: startServices = [{ notifications: undefined }] } = useAsync(getStartServices);
const [{ notifications }] = startServices;
const LazyComponent = useMemo(() => lazy(() => fn().then((x) => ({ default: x }))), [fn]);
if (!notifications) {
return null;
}
return (
<SuspenseErrorBoundary notifications={notifications}>
<LazyComponent {...props} />
</SuspenseErrorBoundary>
);
};