withApi.tsx 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import {Client} from 'sentry/api';
  2. import getDisplayName from 'sentry/utils/getDisplayName';
  3. import useApi from 'sentry/utils/useApi';
  4. type InjectedApiProps = {
  5. api: Client;
  6. };
  7. type WrappedProps<P> = Omit<P, keyof InjectedApiProps> & Partial<InjectedApiProps>;
  8. /**
  9. * XXX: Prefer useApi if you are wrapping a Function Component!
  10. *
  11. * React Higher-Order Component (HoC) that provides "api" client when mounted,
  12. * and clears API requests when component is unmounted.
  13. *
  14. * If an `api` prop is provided when the component is invoked it will be passed
  15. * through.
  16. */
  17. const withApi = <P extends InjectedApiProps>(
  18. WrappedComponent: React.ComponentType<P>,
  19. options: Parameters<typeof useApi>[0] = {}
  20. ) => {
  21. const WithApi: React.FC<WrappedProps<P>> = ({api: propsApi, ...props}) => {
  22. const api = useApi({api: propsApi, ...options});
  23. return <WrappedComponent {...(props as P)} api={api} />;
  24. };
  25. WithApi.displayName = `withApi(${getDisplayName(WrappedComponent)})`;
  26. return WithApi;
  27. };
  28. export default withApi;