useApi.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import {useEffect, useRef} from 'react';
  2. import {Client} from 'sentry/api';
  3. type Options = {
  4. /**
  5. * An existing API client may be provided.
  6. *
  7. * This is a continent way to re-use clients and still inherit the
  8. * persistInFlight configuration.
  9. */
  10. api?: Client;
  11. /**
  12. * Enabling this option will disable clearing in-flight requests when the
  13. * component is unmounted.
  14. *
  15. * This may be useful in situations where your component needs to finish up
  16. * somewhere the client was passed into some type of action creator and the
  17. * component is unmounted.
  18. */
  19. persistInFlight?: boolean;
  20. };
  21. /**
  22. * Returns an API client that will have it's requests canceled when the owning
  23. * React component is unmounted (may be disabled via options).
  24. */
  25. function useApi({persistInFlight, api: providedApi}: Options = {}) {
  26. const localApi = useRef<Client>();
  27. // Lazily construct the client if we weren't provided with one
  28. if (localApi.current === undefined && providedApi === undefined) {
  29. localApi.current = new Client();
  30. }
  31. // Use the provided client if available
  32. const api = providedApi ?? localApi.current!;
  33. function handleCleanup() {
  34. !persistInFlight && api.clear();
  35. }
  36. useEffect(() => handleCleanup, []);
  37. return api;
  38. }
  39. export default useApi;