queryClient.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import * as reactQuery from '@tanstack/react-query';
  2. import {QueryClientConfig} from '@tanstack/react-query';
  3. import RequestError from 'sentry/utils/requestError/requestError';
  4. import useApi from 'sentry/utils/useApi';
  5. type QueryKeyEndpointOptions = {
  6. query?: Record<string, any>;
  7. };
  8. type QueryKey =
  9. | readonly [url: string]
  10. | readonly [url: string, options: QueryKeyEndpointOptions];
  11. type UseQueryOptions<TQueryFnData, TError, TData, TQueryKey extends QueryKey> = Omit<
  12. reactQuery.UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
  13. 'queryKey' | 'queryFn'
  14. >;
  15. // We are not overriding any defaults options for stale time, retries, etc.
  16. // See https://tanstack.com/query/v4/docs/guides/important-defaults
  17. const DEFAULT_QUERY_CLIENT_CONFIG: QueryClientConfig = {};
  18. /**
  19. * Wraps React Query's useQuery for consistent usage in the Sentry app.
  20. * Query keys should be an array which include an endpoint URL and options such as query params.
  21. * This wrapper will execute the request using the query key URL, but if you need custom behavior
  22. * you may supply your own query function as the second argument.
  23. *
  24. * See https://tanstack.com/query/v4/docs/overview for docs on React Query.
  25. *
  26. * Example usage:
  27. *
  28. * const { data, isLoading, isError } = useQuery<EventsResponse>(['/events', { query: { limit: 50 }}])
  29. */
  30. function useQuery<TQueryFnData, TError = RequestError, TData = TQueryFnData>(
  31. queryKey: QueryKey,
  32. queryFnOrQueryOptions?:
  33. | reactQuery.QueryFunction<TQueryFnData, QueryKey>
  34. | UseQueryOptions<TQueryFnData, TError, TData, QueryKey>,
  35. queryOptions?: UseQueryOptions<TQueryFnData, TError, TData, QueryKey>
  36. ) {
  37. const api = useApi();
  38. const [path, endpointOptions] = queryKey;
  39. const defaultQueryFn: reactQuery.QueryFunction<TQueryFnData, QueryKey> = () =>
  40. api.requestPromise(path, {
  41. method: 'GET',
  42. query: endpointOptions?.query,
  43. });
  44. const queryFn =
  45. typeof queryFnOrQueryOptions === 'function' ? queryFnOrQueryOptions : defaultQueryFn;
  46. return reactQuery.useQuery(queryKey, queryFn, queryOptions);
  47. }
  48. // eslint-disable-next-line import/export
  49. export * from '@tanstack/react-query';
  50. // eslint-disable-next-line import/export
  51. export {DEFAULT_QUERY_CLIENT_CONFIG, useQuery};