Skip to content

Commit

Permalink
feat: Add boolean support
Browse files Browse the repository at this point in the history
Closes #196.
  • Loading branch information
franky47 committed Feb 26, 2021
1 parent 09b3a6a commit 0589db1
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
7 changes: 6 additions & 1 deletion src/defs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ export type HistoryOptions = 'replace' | 'push'

export type Serializers<T> = {
parse: (value: string) => T | null
serialize: (value: T) => string
serialize: (value: T) => string | null
}

export type QueryTypeMap = {
string: Serializers<string>
integer: Serializers<number>
float: Serializers<number>
boolean: Serializers<boolean>
timestamp: Serializers<Date>
isoDateTime: Serializers<Date>
}
Expand All @@ -26,6 +27,10 @@ export const queryTypes: QueryTypeMap = {
parse: v => parseFloat(v),
serialize: v => v.toString()
},
boolean: {
parse: v => Boolean(v) || v === '',
serialize: (v: boolean) => (v ? '' : null)
},
timestamp: {
parse: v => new Date(v),
serialize: (v: Date) => v.valueOf().toString()
Expand Down
12 changes: 9 additions & 3 deletions src/useQueryState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,17 @@ export function useQueryState<T = string>(
// unnecessary renders when other query parameters change.
// URLSearchParams is already polyfilled by Next.js
const query = new URLSearchParams(window.location.search)
if (newValue) {
query.set(key, serialize(newValue))
} else {
if (!newValue) {
// Don't leave value-less keys hanging
query.delete(key)
} else {
const serialized = serialize(newValue)
if (serialized) {
query.set(key, serialized)
} else {
// Serializers can return null to unset keys
query.delete(key)
}
}

// Remove fragment and query from asPath
Expand Down
7 changes: 6 additions & 1 deletion src/useQueryStates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,12 @@ export function useQueryStates<T extends object>(
query.delete(key)
} else if (newValue !== undefined) {
const { serialize } = keys[key as keyof T]
query.set(key, serialize(newValue as T[keyof T]))
const serialized = serialize(newValue as T[keyof T])
if (serialized) {
query.set(key, serialized)
} else {
query.delete(key)
}
}
})

Expand Down

0 comments on commit 0589db1

Please sign in to comment.