Last active
June 20, 2025 13:50
-
-
Save asadulloh-pro/1e1ca22784c2ae064061fe5c18b59fa1 to your computer and use it in GitHub Desktop.
next/router dan useSearchParams ni olib ishlatish biroz noqulaylik tug'diradi. Men qolbola hook yasab shu holatda ishlataman.
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
import { usePathname, useSearchParams } from 'next/navigation'; | |
import { useRouter } from 'next/router'; | |
import { useCallback } from 'react'; | |
const useAppSearchParams = () => { | |
const searchParams = useSearchParams(); | |
const pathname = usePathname(); | |
const { replace } = useRouter(); | |
const setSearchParams = useCallback( | |
<K extends string | string[]>( | |
key: K, | |
value: K extends string ? string : Array<string | number | never[]> | |
) => { | |
if (typeof key === 'object') { | |
const params = new URLSearchParams(searchParams?.toString()); | |
key.forEach((elem, index) => { | |
if (typeof value[index] !== 'object') { | |
params.set(elem, String(value[index])); | |
} else { | |
const data = Array.from(value[index]); | |
if (data.length) { | |
params.set(elem, encodeURI(data.toString())); | |
} else { | |
params.delete(elem); | |
} | |
} | |
}); | |
replace(`${pathname}?${params.toString().replace(/%2C/g, ',')}`); | |
} else { | |
const params = new URLSearchParams(searchParams?.toString()); | |
if (typeof value !== 'number' && !value) { | |
params.delete(key); | |
} else { | |
params.set( | |
key, | |
typeof value !== 'object' | |
? String(value) | |
: encodeURI(Array(value).toString()) | |
); | |
} | |
replace(`${pathname}?${params.toString().replace(/%2C/g, ',')}`); | |
} | |
}, | |
[pathname, replace, searchParams] | |
); | |
const deleteSearchPrams = useCallback( | |
(key: string | string[] | null) => { | |
if (key === null) { | |
const params = new URLSearchParams(); | |
window.history.pushState(null, '', `?${params.toString()}`); | |
} else if (typeof key === 'object') { | |
const params = new URLSearchParams(searchParams?.toString()); | |
key.forEach((elem) => { | |
params.delete(elem); | |
}); | |
replace(`${pathname}?${params.toString()}`); | |
} else { | |
const params = new URLSearchParams(searchParams?.toString()); | |
params.delete(key); | |
replace(`${pathname}?${params.toString()}`); | |
} | |
}, | |
[pathname, replace, searchParams] | |
); | |
return { setSearchParams, deleteSearchPrams, searchParams }; | |
}; | |
export default useAppSearchParams; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment