Skip to content

Commit bd47ff3

Browse files
Update useSearchParams.ts
Update useSearchParams.ts
1 parent 91924d1 commit bd47ff3

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

hooks/useSearchParams.ts

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,34 @@ export function useSearchParams<T extends Record<string, string>>() {
3434
/**
3535
* Handles the popstate event to update parameters when navigation occurs.
3636
*/
37-
const handlePopState = () => {
37+
const handleUrlChange = () => {
3838
setParams(getParams());
3939
};
4040

41-
window.addEventListener("popstate", handlePopState);
41+
// Override pushState and replaceState to detect SPA navigations
42+
const originalPushState = history.pushState;
43+
const originalReplaceState = history.replaceState;
44+
45+
history.pushState = function (...args) {
46+
const result = originalPushState.apply(this, args);
47+
handleUrlChange();
48+
return result;
49+
};
50+
51+
history.replaceState = function (...args) {
52+
const result = originalReplaceState.apply(this, args);
53+
handleUrlChange();
54+
return result;
55+
};
56+
57+
// Listen to back/forward button
58+
window.addEventListener("popstate", handleUrlChange);
59+
60+
// Cleanup function
4261
return () => {
43-
window.removeEventListener("popstate", handlePopState);
62+
window.removeEventListener("popstate", handleUrlChange);
63+
history.pushState = originalPushState;
64+
history.replaceState = originalReplaceState;
4465
};
4566
}, []);
4667

@@ -49,8 +70,8 @@ export function useSearchParams<T extends Record<string, string>>() {
4970
* @param {Partial<T>} newParams - The new parameters to update.
5071
* @param {boolean} [clear=false] - Whether to clear all existing parameters before setting new ones.
5172
*/
52-
const updateSearchParams = (
53-
newParams: Partial<T>,
73+
const updateSearchParams = <Params extends T>(
74+
newParams: Partial<Params>,
5475
clear: boolean = false
5576
) => {
5677
const searchParams = clear
@@ -74,5 +95,5 @@ export function useSearchParams<T extends Record<string, string>>() {
7495
setParams({} as T);
7596
};
7697

77-
return { params, updateSearchParams, clearSearchParams };
98+
return { params, updateSearchParams, clearSearchParams, getParams };
7899
}

0 commit comments

Comments
 (0)