Skip to content

Commit 7a5815e

Browse files
authored
fix(use-query-params): correct infinite loop when search is empty (#94)
1 parent 651adce commit 7a5815e

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

packages/use-query-params/src/__tests__/index.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,4 +239,25 @@ describe('useQueryParam', () => {
239239
names: ['John', '', 'Jane', '', '', ''],
240240
})
241241
})
242+
243+
test('should work correctly when search is empty', () => {
244+
jest.useFakeTimers()
245+
const { result } = renderHook(() => useQueryParam(), {
246+
wrapper: wrapper({ search: '' }),
247+
})
248+
249+
act(() => {
250+
result.current.setQueryParams({ name: 'John' })
251+
})
252+
jest.runAllTimers()
253+
expect(result.current.queryParams).toEqual({
254+
name: 'John',
255+
})
256+
257+
act(() => {
258+
result.current.replaceQueryparams({})
259+
})
260+
jest.runAllTimers()
261+
expect(result.current.queryParams).toEqual({})
262+
})
242263
})

packages/use-query-params/src/index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,11 @@ const useQueryParams = () => {
5050
useEffect(() => {
5151
const handler = setTimeout(() => {
5252
const stringifiedParams = stringyFormat(state)
53-
if (search !== `?${stringifiedParams}`)
53+
const searchToCompare = search || '?'
54+
55+
if (searchToCompare !== `?${stringifiedParams}`) {
5456
replace(`${pathname}?${stringifiedParams}`)
57+
}
5558
}, 500)
5659

5760
return () => {

0 commit comments

Comments
 (0)