Skip to content

Commit

Permalink
Create navigation helper library
Browse files Browse the repository at this point in the history
  • Loading branch information
carina-akaia committed Jul 3, 2024
1 parent 23a27d5 commit 0acc8be
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/common/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export { default as truncate } from "./truncate";
export { default as formatWithCommas } from "./formatWithCommas";
export * from "./yoctosToUsdWithFallback";
export * from "./converters";
export * from "./navigation";
39 changes: 39 additions & 0 deletions src/common/lib/navigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { useCallback, useMemo } from "react";

import { usePathname, useRouter, useSearchParams } from "next/navigation";

/**
* Provides a method to update the search parameters for the current URL,
* without changing the route path itself.
*
* @example
* const { syncRouteParams } = useSearchParamsNavigation();
*
* syncRouteParams({ accountId: "root.near" });
*/
export const useSearchParamsNavigation = (): {
syncRouteParams: (newParams: Record<string, string>) => void;
} => {
const router = useRouter();
const pathname = usePathname();
const currentQueryString = useSearchParams().toString();

const searchParamsDecoded = useMemo(
() => new URLSearchParams(currentQueryString),
[currentQueryString],
);

const syncRouteParams = useCallback(
(newParams: Record<string, string>) => {
Object.entries(newParams).forEach(([key, value]) =>
searchParamsDecoded.set(key, value),
);

router.push(`${pathname}?${searchParamsDecoded.toString()}`);
},

[pathname, router, searchParamsDecoded],
);

return { syncRouteParams };
};

0 comments on commit 0acc8be

Please sign in to comment.