You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.7KB

  1. import { useLocation, useNavigate } from "react-router";
  2. import { Dictionary } from "@types";
  3. import { PageID } from "pages";
  4. import { getPath } from "routes/path";
  5. import { scrollToTop } from "utils/page";
  6. export default function useNavigateCustom() {
  7. const navigate = useNavigate();
  8. const { pathname, search } = useLocation();
  9. const navigateWhenChanged = (
  10. path: string,
  11. param?: Dictionary | URLSearchParams | string,
  12. option?: {
  13. reload?: boolean;
  14. context?: any;
  15. }
  16. ) => {
  17. const currentUrl = pathname + search;
  18. let newPath = path;
  19. if (typeof param === "string") {
  20. if (!param.startsWith("?")) {
  21. newPath += "?";
  22. }
  23. newPath += param;
  24. } else if (param instanceof URLSearchParams) {
  25. const search = param.toString();
  26. if (search) {
  27. newPath += "?";
  28. newPath += search;
  29. }
  30. } else if (typeof param === "object") {
  31. const urlParam = new URLSearchParams(param);
  32. const search = urlParam.toString();
  33. if (search) {
  34. newPath += "?";
  35. newPath += search;
  36. }
  37. }
  38. if (currentUrl !== newPath || option?.reload) {
  39. if (option?.context) {
  40. console.log("navigate to", newPath, option.context);
  41. }
  42. // 同じURLで遷移要求があった場合、reload設定されていれば同じページを読み込みなおす
  43. // 一旦、空白のページを経由する必要がある
  44. if (currentUrl === newPath && option?.reload) {
  45. navigate(getPath(PageID.DASHBOARD_ENPTY));
  46. setTimeout(() => {
  47. navigate(newPath);
  48. }, 50);
  49. } else {
  50. navigate(newPath);
  51. }
  52. }
  53. scrollToTop("auto");
  54. };
  55. return { navigate, navigateWhenChanged };
  56. }