Skip to content

Commit

Permalink
fix: reset state independent from URL in 'reset' cb
Browse files Browse the repository at this point in the history
  • Loading branch information
asmyshlyaev177 committed Jan 30, 2025
1 parent d7233df commit 9392a19
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
24 changes: 24 additions & 0 deletions packages/urlstate/useUrlStateBase/useUrlStateBase.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,30 @@ describe('useUrlStateBase', () => {
expect(result.current.state).toStrictEqual(shape);
});

test('reset state independent from URL', async () => {
vi.useFakeTimers({
toFake: ['setTimeout']
});
vi.mocked(utils).isSSR = false;

const { result } = renderHook(() => useUrlStateBase(shape, router));

act(() => {
result.current.updateState({ str: 'test'});
})
expect(result.current.state).toStrictEqual({...shape, str: 'test' });

act(() => {
result.current.reset();
})
await vi.advanceTimersByTime(700);
await vi.advanceTimersByTime(700);

expect(router.replace).not.toHaveBeenCalled()
expect(router.push).not.toHaveBeenCalledTimes(1)
expect(result.current.state).toStrictEqual(shape);
});

test('with replace', async () => {
vi.useFakeTimers({
toFake: ['setTimeout']
Expand Down
7 changes: 4 additions & 3 deletions packages/urlstate/useUrlStateBase/useUrlStateBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,15 @@ export function useUrlStateBase<T extends JSONCompatible>(
...getState(),
...value,
};

setState(newVal);

const qStr = stringify(newVal, getOtherParams(defaultState));

const newUrl = `${window.location.pathname}${qStr.length ? "?" : ""}${qStr}${window.location.hash}`;
const currUrl = `${window.location.pathname}${window.location.search}${window.location.hash}`;
if (newUrl === currUrl) return;

setState(newVal);

const { replace, ..._rest } = options || {};
queue.current.push([replace ? "replace" : "push", newUrl, _rest]);

Expand All @@ -123,7 +124,7 @@ export function useUrlStateBase<T extends JSONCompatible>(
(options?: Options) => {
updateUrl(defaultState, options);
},
[updateUrl],
[updateUrl, setState],
);

return {
Expand Down

0 comments on commit 9392a19

Please sign in to comment.