import { useCallback , useEffect , useState } from 'react' ; import { useHistory , useRouteMatch , generatePath } from 'react-router' ; import { UrlParamTransform } from './url-param-transform' ; export function useUrlParam < T > ( param , paramTransform , pathPattern ? , defaultParams = { } ) { const match = useRouteMatch ( ) ; const history = useHistory ( ) ; const [ paramValue , setParamValue ] = useState < T > ( ) ; useEffect ( ( ) => { const stringValue = match . params [ param ] ; setParamValue ( stringValue && paramTransform . fromParam ( stringValue ) ) ; } , [ param , paramTransform , match . url ] ) ; const setUrlParam = useCallback ( ( value ) => { const newParams = Object . assign ( { } , defaultParams , match . params ) ; newParams [ param ] = value == undefined ? undefined : paramTransform . toParam ( value ) ; const newPath = generatePath ( pathPattern ?? match . path , newParams ) ; history . push ( newPath ) ; } , [ param , paramTransform , pathPattern , defaultParams , match . url ] ) ; return [ paramValue , setUrlParam ] ; }