routeAnalyticsContextProvider.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. };
  10. /**
  11. * This context is used to set analytics params for route based analytics.
  12. * It is used by multiple different hooks and an HoC, each with
  13. * slightly different use cases.
  14. */
  15. export const RouteAnalyticsContext = createContext<{
  16. setDisableRouteAnalytics: () => void;
  17. setOrganization: (organization: Organization) => void;
  18. setRouteAnalyticsParams: (params: Record<string, any>) => void;
  19. }>(DEFAULT_CONTEXT);
  20. interface Props extends RouteContextInterface {
  21. children?: React.ReactNode;
  22. }
  23. export default function RouteAnalyticsContextProvider({children, ...props}: Props) {
  24. const useRouteActivatedHook = HookStore.get('react-hook:route-activated')[0];
  25. const {setDisableRouteAnalytics, setRouteAnalyticsParams, setOrganization} =
  26. useRouteActivatedHook?.(props) || DEFAULT_CONTEXT;
  27. const memoizedValue = useMemo(
  28. () => ({
  29. setDisableRouteAnalytics,
  30. setRouteAnalyticsParams,
  31. setOrganization,
  32. }),
  33. [setDisableRouteAnalytics, setRouteAnalyticsParams, setOrganization]
  34. );
  35. return (
  36. <RouteAnalyticsContext.Provider value={memoizedValue}>
  37. {children}
  38. </RouteAnalyticsContext.Provider>
  39. );
  40. }