lastKnownRouteContextProvider.tsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import {createContext, useContext, useEffect, useRef} from 'react';
  2. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  3. import {useRoutes} from 'sentry/utils/useRoutes';
  4. interface Props {
  5. children: React.ReactNode;
  6. }
  7. export const LastKnownRouteContext = createContext<string>('<unknown>');
  8. export function useLastKnownRoute() {
  9. return useContext(LastKnownRouteContext);
  10. }
  11. /**
  12. * This provider tracks the last known route that the user has navigated to.
  13. * This is used to better group issues when we hit "route not found" errors.
  14. */
  15. export default function LastKnownRouteContextProvider({children}: Props) {
  16. const route = useRoutes();
  17. // We could use `usePrevious` here if we didn't need the additional logic to
  18. // ensure we don't track the not found route, which isn't useful for issue grouping.
  19. const prevRoute = useRef(route);
  20. useEffect(() => {
  21. // only store the new value if it's not the "not found" route
  22. if (getRouteStringFromRoutes(route) !== '/*') {
  23. prevRoute.current = route;
  24. }
  25. }, [route]);
  26. const lastKnownRoute = getRouteStringFromRoutes(prevRoute.current);
  27. return (
  28. <LastKnownRouteContext.Provider value={lastKnownRoute}>
  29. {children}
  30. </LastKnownRouteContext.Provider>
  31. );
  32. }