Skip to content

Instantly share code, notes, and snippets.

@wscnd
Created July 10, 2021 21:49
Show Gist options
  • Select an option

  • Save wscnd/3bb5e6805c6f567d8c62c50fc8ac97f6 to your computer and use it in GitHub Desktop.

Select an option

Save wscnd/3bb5e6805c6f567d8c62c50fc8ac97f6 to your computer and use it in GitHub Desktop.
const getSearchParams = <T extends object>(): Partial<T> => {
// server side rendering
if (typeof window === "undefined") {
return {};
}
const params = new URLSearchParams(window.location.search);
return new Proxy(params, {
get(target, prop, receiver) {
return target.get(prop as string) || undefined;
},
}) as T;
};
export const useSearchParams = <T extends object = any>(): Partial<T> => {
const [searchParams, setSearchParams] = useState(getSearchParams());
useEffect(() => {
setSearchParams(getSearchParams());
}, [typeof window === "undefined" ? "once" : window.location.search]);
return searchParams;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment