Skip to content

Commit

Permalink
Implement search parameters cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
carina-akaia committed Jul 4, 2024
1 parent 0acc8be commit b34ea3d
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/common/lib/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@ import { useCallback, useMemo } from "react";

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

export type RouteParams = Record<string, string | undefined>;

/**
* Provides a method to update the search parameters for the current URL,
* without changing the route path itself.
*
* @example
* const { syncRouteParams } = useSearchParamsNavigation();
*
* // Sets `accountId` search parameter to "root.near"
* syncRouteParams({ accountId: "root.near" });
*
* // Deletes `transactionHashes` search parameter
* syncRouteParams({ transactionHashes: undefined });
*/
export const useSearchParamsNavigation = (): {
syncRouteParams: (newParams: Record<string, string>) => void;
} => {
export const useSearchParamsNavigation = () => {
const router = useRouter();
const pathname = usePathname();
const currentQueryString = useSearchParams().toString();
Expand All @@ -24,9 +28,11 @@ export const useSearchParamsNavigation = (): {
);

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

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

0 comments on commit b34ea3d

Please sign in to comment.