Created
July 10, 2021 21:49
-
-
Save wscnd/3bb5e6805c6f567d8c62c50fc8ac97f6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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