import * as t from 'io-ts' ; import { useLocation , useParams } from 'react-router-dom' ; import { isLeft } from 'fp-ts/lib/Either' ; import { PathReporter } from 'io-ts/lib/PathReporter' ; import { Params , RouteParams , routes } from '../routes' ; function getQueryParams ( location ) { const urlSearchParms = new URLSearchParams ( location . search ) ; const queryParams = { } ; urlSearchParms . forEach ( ( value , key ) => { queryParams [ key ] = value ; } ) ; return queryParams ; } param params export function useRouteParams < T extends keyof typeof routes > ( pathName ) { const location = useLocation ( ) ; const pathParams = useParams ( ) ; const queryParams = getQueryParams ( location ) ; const { query , path } = routes [ pathName ] . params as Params ; const rts = { queryRt : query ? t . exact ( query ) : t . strict ( { } ) , pathRt : path ? t . exact ( path ) : t . strict ( { } ) , } ; const queryResult = rts . queryRt . decode ( queryParams ) ; const pathResult = rts . pathRt . decode ( pathParams ) ; if ( isLeft ( queryResult ) ) { console . error ( PathReporter . report ( queryResult ) [ 0 ] ) ; } if ( isLeft ( pathResult ) ) { console . error ( PathReporter . report ( pathResult ) [ 0 ] ) ; } return { query : isLeft ( queryResult ) ? { } : queryResult . right , path : isLeft ( pathResult ) ? { } : pathResult . right , } as unknown as RouteParams < T > ; }