Spaces:
Running
Running
File size: 1,368 Bytes
1a56472 5c42f3b 1a56472 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import { useSyncExternalStore } from "react";
const subscribe = (callback: (searchParams: string) => void) => {
const listener = () => {
callback(window.location.search);
};
window.addEventListener("popstate", listener);
return () => {
window.removeEventListener("popstate", listener);
};
};
const getSnapshot = () => {
return window.location.search;
};
const getServerSnapshot = () => {
return window.location.search;
};
const setSearchParams = (searchParams: Record<string, string>) => {
const url = new URL(window.location.href);
Object.entries(searchParams).forEach(([key, value]) => {
if (value === undefined || value === null || value === "") {
url.searchParams.delete(key);
} else {
url.searchParams.set(key, value);
}
});
window.history.pushState({}, "", url);
window.dispatchEvent(new PopStateEvent("popstate"));
};
export const useSearchParams = () => {
// using useSyncExternalStore to get the search params
// when the url changes, emit the new value and convert it to an object
// return an additional setter to update the search params with an object that is converted to a string and merged with the existing search params
const searchParams = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot
);
return {
searchParams,
setSearchParams,
};
};
|