Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 3 additions & 1 deletion src/useSearchParam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const useSearchParam: UseQueryParam = (param) => {
setValue(getValue(location.search, param));
};

onChange();

on(window, 'popstate', onChange);
on(window, 'pushstate', onChange);
on(window, 'replacestate', onChange);
Expand All @@ -23,7 +25,7 @@ const useSearchParam: UseQueryParam = (param) => {
off(window, 'pushstate', onChange);
off(window, 'replacestate', onChange);
};
}, []);
}, [param]);

return value;
};
Expand Down
32 changes: 32 additions & 0 deletions tests/useSearchParam.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,38 @@ it('returns null if search param not found', () => {
expect(result.current).toBe(null);
});

it('reads the new parameter when its name changes', () => {
mockSearch = 'foo=bar&baz=quux';
const { result, rerender } = renderHook(({ param }) => useSearchParam(param), {
initialProps: { param: 'foo' },
});

rerender({ param: 'baz' });
expect(result.current).toBe('quux');

rerender({ param: 'missing' });
expect(result.current).toBe(null);
});

it.each(['popstate', 'pushstate', 'replacestate'])(
'tracks the new parameter on %s after its name changes',
(event) => {
mockSearch = 'foo=bar&baz=quux';
const { result, rerender, unmount } = renderHook(({ param }) => useSearchParam(param), {
initialProps: { param: 'foo' },
});

rerender({ param: 'baz' });
act(() => {
mockSearch = 'foo=1&baz=2';
window.dispatchEvent(new Event(event));
});

expect(result.current).toBe('2');
unmount();
}
);

it('tracks the latest search param value', () => {
mockSearch = 'foo=bar&baz=quux';

Expand Down