Skip to content

Commit

Permalink
fix(useUrlSearchParams): wrong iterable empty check (vitest-dev#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
lstoeferle committed Feb 25, 2021
1 parent e66b1c6 commit 839cd86
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 13 deletions.
4 changes: 2 additions & 2 deletions packages/core/useUrlSearchParams/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ describe('useUrlSearchParams', () => {
test('return initial params', () => {
useSetup(() => {
if (mode === 'hash')
mockPopstate('', '#/test/?foo=bar')
window.location.hash = '#/test/?foo=bar'
else
mockPopstate('?foo=bar', '')
window.location.search = '?foo=bar'
})

const params = useUrlSearchParams(mode)
Expand Down
24 changes: 13 additions & 11 deletions packages/core/useUrlSearchParams/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,10 @@ export function useUrlSearchParams<T extends Record<string, any> = UrlParams>(

const write = (params: URLSearchParams, shouldUpdateParamsMap?: boolean) => {
pause()
if (shouldUpdateParamsMap) {
Object.keys(paramsMap).forEach(key => delete paramsMap[key])
for (const key of params.keys()) {
const paramsForKey = params.getAll(key)
writeToParamsMap(key, paramsForKey.length > 1 ? paramsForKey : (params.get(key) || ''))
}
}
if (shouldUpdateParamsMap)
updateParamsMap()

const empty = !params.keys.length
const empty = !params.keys().next()
const query = empty
? hashWithoutParams.value
: (mode === 'hash')
Expand All @@ -64,6 +59,16 @@ export function useUrlSearchParams<T extends Record<string, any> = UrlParams>(

const writeToParamsMap = (key: keyof T, value: any) => paramsMap[key] = value

const updateParamsMap = () => {
Object.keys(paramsMap).forEach(key => delete paramsMap[key])
for (const key of params.keys()) {
const paramsForKey = params.getAll(key)
writeToParamsMap(key, paramsForKey.length > 1 ? paramsForKey : (params.get(key) || ''))
}
}
// Update the paramsMap with initial values
updateParamsMap()

const { pause, resume } = pausableWatch(
paramsMap,
() => {
Expand All @@ -85,8 +90,5 @@ export function useUrlSearchParams<T extends Record<string, any> = UrlParams>(
write(params, true)
})

// Update the paramsMap with initial values
write(params, true)

return paramsMap
}

0 comments on commit 839cd86

Please sign in to comment.