routeAnalyticsContextProvider.tsx 1.8 KB

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