-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
23a27d5
commit 0acc8be
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | ||
}; |