routeAnalyticsContextProvider.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import React, {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. setDisableRouteAnalytics: () => void;
  20. setEventNames: (evetKey: string, eventName: string) => void;
  21. setOrganization: (organization: Organization) => void;
  22. setRouteAnalyticsParams: (params: Record<string, any>) => void;
  23. }>(DEFAULT_CONTEXT);
  24. interface Props extends RouteContextInterface {
  25. children?: React.ReactNode;
  26. }
  27. export default function RouteAnalyticsContextProvider({children, ...props}: Props) {
  28. const useRouteActivatedHook = HookStore.get('react-hook:route-activated')[0];
  29. const {
  30. setDisableRouteAnalytics,
  31. setRouteAnalyticsParams,
  32. setOrganization,
  33. setEventNames,
  34. previousUrl,
  35. } = useRouteActivatedHook?.(props) || DEFAULT_CONTEXT;
  36. const memoizedValue = useMemo(
  37. () => ({
  38. setDisableRouteAnalytics,
  39. setRouteAnalyticsParams,
  40. setOrganization,
  41. setEventNames,
  42. previousUrl,
  43. }),
  44. [
  45. setDisableRouteAnalytics,
  46. setRouteAnalyticsParams,
  47. setOrganization,
  48. setEventNames,
  49. previousUrl,
  50. ]
  51. );
  52. return (
  53. <RouteAnalyticsContext.Provider value={memoizedValue}>
  54. {children}
  55. </RouteAnalyticsContext.Provider>
  56. );
  57. }