Last active
December 3, 2024 14:31
-
-
Save bernardinorafael/9656bc648953f1dbe1a91e4a5c6b83ad to your computer and use it in GitHub Desktop.
useSearchParams React Hook
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
import React from 'react' | |
import { useRouter } from 'next/router' | |
export function useSearchParams() { | |
const router = useRouter() | |
const isClientSide = typeof window !== 'undefined' | |
const set = React.useCallback( | |
(key: string, v: string | number | boolean) => { | |
if (!isClientSide) return | |
const url = new URL(window.location.href) | |
const params = new URLSearchParams(url.search) | |
if (!v || (typeof v === 'string' && v.length === 0)) { | |
params.delete(key) | |
} else { | |
params.set(key, String(v)) | |
} | |
router.replace(`${url.pathname}?${params.toString()}`, undefined, { | |
shallow: true, | |
}) | |
}, | |
[router, isClientSide] | |
) | |
const remove = React.useCallback( | |
(keys: string[]) => { | |
if (!isClientSide) return | |
const url = new URL(window.location.href) | |
const params = new URLSearchParams(url.search) | |
keys.forEach((key) => { | |
params.delete(key) | |
}) | |
router.replace(`${url.pathname}?${params.toString()}`, undefined, { | |
shallow: true, | |
}) | |
}, | |
[router, isClientSide] | |
) | |
const get = React.useCallback( | |
<T = string,>(key: string, fn?: (v: string | null) => T): T | null => { | |
if (!isClientSide) return null | |
const params = new URLSearchParams(window.location.search) | |
const val = params.get(key) | |
if (fn) { | |
return fn(val) | |
} | |
return val as unknown as T | |
}, | |
[isClientSide] | |
) | |
return { set, remove, get } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment