1- import { ParsedQuery , parse , stringify } from 'query-string'
1+ import { parse , stringify } from 'query-string'
22import { useCallback , useMemo } from 'react'
33import { useLocation , useNavigate } from 'react-router-dom'
44
@@ -7,12 +7,18 @@ interface Options {
77 push : boolean
88}
99
10- const useQueryParams = ( ) : {
11- queryParams : ParsedQuery < string | number | boolean >
10+ type QueryParamValue = string | number | boolean | null | undefined
11+
12+ type QueryParams = {
13+ [ key : string ] : QueryParamValue | Array < QueryParamValue >
14+ }
15+
16+ const useQueryParams = < T extends QueryParams > ( ) : {
17+ queryParams : T
1218 /**
1319 * Replace the query params in the url. It erase all current values and put the new ones
1420 *
15- * @param newParams - The values to set in the query string, overweriting existing one
21+ * @param newParams - The values to set in the query string, overwriting existing one
1622 * @param options - Options to define behavior
1723 */
1824 replaceQueryParams : typeof replaceQueryParams
@@ -33,12 +39,12 @@ const useQueryParams = (): {
3339 arrayFormat : 'comma' ,
3440 parseBooleans : true ,
3541 parseNumbers : true ,
36- } ) ,
42+ } ) as T ,
3743 [ location . search ] ,
3844 )
3945
4046 const stringyFormat = useCallback (
41- ( params : Record < string , unknown > ) : string =>
47+ ( params : Partial < T > ) : string =>
4248 stringify ( params , {
4349 arrayFormat : 'comma' ,
4450 skipEmptyString : true ,
@@ -49,7 +55,7 @@ const useQueryParams = (): {
4955 )
5056
5157 const replaceInUrlIfNeeded = useCallback (
52- ( newState : Record < string , unknown > , options ?: Options ) => {
58+ ( newState : T , options ?: Options ) => {
5359 const stringifiedParams = stringyFormat ( newState )
5460 const searchToCompare = location . search || '?'
5561
@@ -63,14 +69,14 @@ const useQueryParams = (): {
6369 )
6470
6571 const setQueryParams = useCallback (
66- ( nextParams : Record < string , unknown > , options ?: Options ) : void => {
72+ ( nextParams : Partial < T > , options ?: Options ) : void => {
6773 replaceInUrlIfNeeded ( { ...currentState , ...nextParams } , options )
6874 } ,
6975 [ currentState , replaceInUrlIfNeeded ] ,
7076 )
7177
7278 const replaceQueryParams = useCallback (
73- ( newParams : Record < string , unknown > , options ?: Options ) : void => {
79+ ( newParams : T , options ?: Options ) : void => {
7480 replaceInUrlIfNeeded ( newParams , options )
7581 } ,
7682 [ replaceInUrlIfNeeded ] ,
0 commit comments