useNavigate.tsx 1002 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import {useCallback, useEffect, useRef} from 'react';
  2. import {useRouteContext} from 'sentry/utils/useRouteContext';
  3. type NavigateOptions = {
  4. replace?: boolean;
  5. state?: any;
  6. };
  7. export function useNavigate() {
  8. const route = useRouteContext();
  9. const navigator = route.router;
  10. const hasMountedRef = useRef(false);
  11. useEffect(() => {
  12. hasMountedRef.current = true;
  13. });
  14. const navigate = useCallback(
  15. (to: string | number, options: NavigateOptions = {}) => {
  16. if (!hasMountedRef.current) {
  17. throw new Error(
  18. `You should call navigate() in a React.useEffect(), not when your component is first rendered.`
  19. );
  20. }
  21. if (typeof to === 'number') {
  22. return navigator.go(to);
  23. }
  24. const nextState = {
  25. pathname: to,
  26. state: options.state,
  27. };
  28. if (options.replace) {
  29. return navigator.replace(nextState);
  30. }
  31. return navigator.push(nextState);
  32. },
  33. [navigator]
  34. );
  35. return navigate;
  36. }