routeAnalyticsContextProvider.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {createContext, useMemo} from 'react';
  2. import HookStore from 'sentry/stores/hookStore';
  3. import type {RouteContextInterface} from 'sentry/types/legacyReactRouter';
  4. import type {Organization} from 'sentry/types/organization';
  5. import {useLocation} from 'sentry/utils/useLocation';
  6. import {useParams} from 'sentry/utils/useParams';
  7. import useRouter from 'sentry/utils/useRouter';
  8. import {useRoutes} from 'sentry/utils/useRoutes';
  9. const DEFAULT_CONTEXT = {
  10. setDisableRouteAnalytics: () => {},
  11. setRouteAnalyticsParams: () => {},
  12. setOrganization: () => {},
  13. setEventNames: () => {},
  14. previousUrl: '',
  15. };
  16. /**
  17. * This context is used to set analytics params for route based analytics.
  18. * It is used by multiple different hooks and an HoC, each with
  19. * slightly different use cases.
  20. */
  21. export const RouteAnalyticsContext = createContext<{
  22. previousUrl: string;
  23. /**
  24. * Enable/disable route analytics manually
  25. * @param disabled - defaults to true
  26. */
  27. setDisableRouteAnalytics: (disabled?: boolean) => void;
  28. setEventNames: (evetKey: string, eventName: string) => void;
  29. setOrganization: (organization: Organization) => void;
  30. setRouteAnalyticsParams: (params: Record<string, any>) => void;
  31. }>(DEFAULT_CONTEXT);
  32. interface Props {
  33. children?: React.ReactNode;
  34. }
  35. export default function RouteAnalyticsContextProvider({children}: Props) {
  36. const useRouteActivatedHook = HookStore.get('react-hook:route-activated')[0];
  37. const context: RouteContextInterface = {
  38. params: useParams(),
  39. routes: useRoutes(),
  40. router: useRouter(),
  41. location: useLocation(),
  42. };
  43. const {
  44. setDisableRouteAnalytics,
  45. setRouteAnalyticsParams,
  46. setOrganization,
  47. setEventNames,
  48. previousUrl,
  49. } = useRouteActivatedHook?.(context) || DEFAULT_CONTEXT;
  50. const memoizedValue = useMemo(
  51. () => ({
  52. setDisableRouteAnalytics,
  53. setRouteAnalyticsParams,
  54. setOrganization,
  55. setEventNames,
  56. previousUrl,
  57. }),
  58. [
  59. setDisableRouteAnalytics,
  60. setRouteAnalyticsParams,
  61. setOrganization,
  62. setEventNames,
  63. previousUrl,
  64. ]
  65. );
  66. return (
  67. <RouteAnalyticsContext.Provider value={memoizedValue}>
  68. {children}
  69. </RouteAnalyticsContext.Provider>
  70. );
  71. }