Created
June 24, 2024 01:35
-
-
Save Iamsheye/0adfe1098d4cfcaaeaaf0405dc13a647 to your computer and use it in GitHub Desktop.
managing state in url
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 { useRouter, useSearchParams, usePathname } from 'next/navigation'; | |
import { useEffect, useState } from 'react'; | |
type UseSearchParamStateReturn<T> = [T, (newValue: T) => void]; | |
const useSearchParamState = <T>(param: string, defaultValue: T): UseSearchParamStateReturn<T> => { | |
const router = useRouter(); | |
const pathname = usePathname(); | |
const searchParams = useSearchParams(); | |
const [value, setValue] = useState<T>(defaultValue); | |
useEffect(() => { | |
const paramValue = searchParams.get(param); | |
if (paramValue !== null) { | |
try { | |
const parsedValue = JSON.parse(paramValue); | |
setValue(parsedValue); | |
} catch (error) { | |
console.error('Failed to parse search param:', error); | |
} | |
} | |
}, [searchParams, param]); | |
const updateSearchParam = (newValue: T) => { | |
const stringifiedValue = JSON.stringify(newValue); | |
const newSearchParams = new URLSearchParams(searchParams.toString()); | |
newSearchParams.set(param, stringifiedValue); | |
router.replace(`${pathname}?${newSearchParams.toString()}`); | |
setValue(newValue); | |
}; | |
return [value, updateSearchParam]; | |
}; | |
export default useSearchParamState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment