@@ -4,24 +4,19 @@ interface UrlQueryObject {
4
4
[ key : string ] : string | number | boolean ;
5
5
}
6
6
7
- // here you can override the parsers for specific query params
8
- // an example is the filter, which must allow filtering by numeric codes
9
- // if this is parsed as numeric, the query param changes filter=0300 to filter=300
10
- // which then does not match against codes, as the filter is usually a 'startsWith'
11
- const DefaultParsers : Record <
12
- string ,
13
- ( value : string ) => string | boolean | number
14
- > = {
15
- filter : ( value : string ) => value ,
16
- } ;
17
-
18
- export const useUrlQuery = ( ) => {
7
+ interface useUrlQueryProps {
8
+ // an array of keys - the values of which should not be parsed before returning
9
+ // by default the value of parameters will be coerced to a number if !isNaN
10
+ // and to boolean if 'true' or 'false'. Specify keys here if you wish to opt out of this
11
+ skipParse ?: string [ ] ;
12
+ }
13
+ export const useUrlQuery = ( { skipParse = [ ] } : useUrlQueryProps ) => {
19
14
const [ searchParams , setSearchParams ] = useSearchParams ( ) ;
20
15
21
16
const updateQuery = ( values : UrlQueryObject , overwrite = false ) => {
22
17
const newQueryObject = overwrite
23
18
? { }
24
- : { ...parseSearchParams ( searchParams ) } ;
19
+ : { ...parseSearchParams ( searchParams , skipParse ) } ;
25
20
Object . entries ( values ) . forEach ( ( [ key , value ] ) => {
26
21
if ( ! value ) delete newQueryObject [ key ] ;
27
22
else newQueryObject [ key ] = value ;
@@ -34,15 +29,20 @@ export const useUrlQuery = () => {
34
29
) ;
35
30
} ;
36
31
37
- return { urlQuery : parseSearchParams ( searchParams ) , updateQuery } ;
32
+ return {
33
+ urlQuery : parseSearchParams ( searchParams , skipParse ) ,
34
+ updateQuery,
35
+ } ;
38
36
} ;
39
37
40
38
// Coerces url params to appropriate type
41
- const parseSearchParams = ( searchParams : URLSearchParams ) =>
39
+ const parseSearchParams = (
40
+ searchParams : URLSearchParams ,
41
+ skipParse : string [ ]
42
+ ) =>
42
43
Object . fromEntries (
43
44
Array . from ( searchParams . entries ( ) ) . map ( ( [ key , value ] ) => {
44
- const parser = DefaultParsers [ key ] ; // written out longhand to avoid TS complaint
45
- if ( parser ) return [ key , parser ( value ) ] ;
45
+ if ( skipParse . includes ( key ) ) return [ key , value ] ;
46
46
if ( ! isNaN ( Number ( value ) ) ) return [ key , Number ( value ) ] ;
47
47
if ( value === 'true' ) return [ key , true ] ;
48
48
if ( value === 'false' ) return [ key , false ] ;
0 commit comments