Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions packages/use-query-params/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ParsedQuery, parse, stringify } from 'query-string'
import { parse, stringify } from 'query-string'
import { useCallback, useMemo } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

Expand All @@ -7,12 +7,18 @@ interface Options {
push: boolean
}

const useQueryParams = (): {
queryParams: ParsedQuery<string | number | boolean>
type QueryParamValue = string | number | boolean | null | undefined

type QueryParams = {
[key: string]: QueryParamValue | Array<QueryParamValue>
}

const useQueryParams = <T extends QueryParams>(): {
queryParams: T
/**
* Replace the query params in the url. It erase all current values and put the new ones
*
* @param newParams - The values to set in the query string, overweriting existing one
* @param newParams - The values to set in the query string, overwriting existing one
* @param options - Options to define behavior
*/
replaceQueryParams: typeof replaceQueryParams
Expand All @@ -33,12 +39,12 @@ const useQueryParams = (): {
arrayFormat: 'comma',
parseBooleans: true,
parseNumbers: true,
}),
}) as T,
[location.search],
)

const stringyFormat = useCallback(
(params: Record<string, unknown>): string =>
(params: Partial<T>): string =>
stringify(params, {
arrayFormat: 'comma',
skipEmptyString: true,
Expand All @@ -49,7 +55,7 @@ const useQueryParams = (): {
)

const replaceInUrlIfNeeded = useCallback(
(newState: Record<string, unknown>, options?: Options) => {
(newState: T, options?: Options) => {
const stringifiedParams = stringyFormat(newState)
const searchToCompare = location.search || '?'

Expand All @@ -63,14 +69,14 @@ const useQueryParams = (): {
)

const setQueryParams = useCallback(
(nextParams: Record<string, unknown>, options?: Options): void => {
(nextParams: Partial<T>, options?: Options): void => {
replaceInUrlIfNeeded({ ...currentState, ...nextParams }, options)
},
[currentState, replaceInUrlIfNeeded],
)

const replaceQueryParams = useCallback(
(newParams: Record<string, unknown>, options?: Options): void => {
(newParams: T, options?: Options): void => {
replaceInUrlIfNeeded(newParams, options)
},
[replaceInUrlIfNeeded],
Expand Down