Skip to content

Commit

Permalink
fix: Use location.pathname as asPath replacement
Browse files Browse the repository at this point in the history
See #282.
  • Loading branch information
franky47 committed Feb 23, 2022
1 parent f020aa6 commit a141483
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 30 deletions.
17 changes: 2 additions & 15 deletions src/useQueryState.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useRouter } from 'next/router'
import React from 'react'
import { HistoryOptions, Serializers, TransitionOptions } from './defs'
import { getPathname } from './internal'

export interface UseQueryStateOptions<T> extends Serializers<T> {
/**
Expand Down Expand Up @@ -257,11 +256,6 @@ export function useQueryState<T = string>(
} else {
query.set(key, serialize(newValue))
}

// Remove fragment and query from asPath
// router.pathname includes dynamic route keys, rather than the route itself,
// e.g. /views/[view] rather than /views/my-view
const asPath = getPathname(router.asPath)
const search = query.toString()
const hash = window.location.hash
return updateUrl?.call(
Expand All @@ -272,21 +266,14 @@ export function useQueryState<T = string>(
search
},
{
pathname: asPath,
pathname: window.location.pathname,
hash,
search
},
transitionOptions
)
},
[
key,
updateUrl,
// Add `asPath` to the dependencies, but only for the path part,
// otherwise as it contains the querystring, this would regenerate
// the state updater function on every query update.
getPathname(router.asPath)
]
[key, updateUrl]
)
return [value ?? defaultValue ?? null, update]
}
17 changes: 2 additions & 15 deletions src/useQueryStates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import type {
Serializers,
TransitionOptions
} from './defs'
import { getPathname } from './internal'

type KeyMapValue<Type> = Serializers<Type> & {
defaultValue?: Type
Expand Down Expand Up @@ -128,11 +127,6 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
query.set(key, serialize(newValue))
}
})

// Remove fragment and query from asPath
// router.pathname includes dynamic route keys, rather than the route itself,
// e.g. /views/[view] rather than /views/my-view
const asPath = getPathname(router.asPath)
const search = query.toString()
const hash = window.location.hash
return updateUrl?.call(
Expand All @@ -143,20 +137,13 @@ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
search
},
{
pathname: asPath,
pathname: window.location.pathname,
hash,
search
}
)
},
[
keys,
updateUrl,
// Add `asPath` to the dependencies, but only for the path part,
// otherwise as it contains the querystring, this would regenerate
// the state updater function on every query update.
getPathname(router.asPath)
]
[keys, updateUrl]
)
return [values, update]
}

0 comments on commit a141483

Please sign in to comment.