Skip to content

Commit 6671855

Browse files
rxliulirschristian
andauthored
feat: Suport for the replace parameter in useLocation().route (#8)
Co-authored-by: Ryan Christian <[email protected]>
1 parent 9281a20 commit 6671855

File tree

3 files changed

+39
-2
lines changed

3 files changed

+39
-2
lines changed

src/router.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ interface LocationHook {
1313
url: string;
1414
path: string;
1515
query: Record<string, string>;
16-
route: (url: string) => void;
16+
route: (url: string, replace?: boolean) => void;
1717
}
1818
export const useLocation: () => LocationHook;
1919

src/router.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ const UPDATE = (state, url) => {
2525
url = link.href.replace(location.origin, '');
2626
} else if (typeof url === 'string') {
2727
push = true;
28+
} else if (url && url.url) {
29+
push = !url.replace;
30+
url = url.url;
2831
} else {
2932
url = location.pathname + location.search;
3033
}
@@ -69,7 +72,13 @@ export function LocationProvider(props) {
6972
const u = new URL(url, location.origin);
7073
const path = u.pathname.replace(/(.)\/$/g, '$1');
7174
// @ts-ignore-next
72-
return { url, path, query: Object.fromEntries(u.searchParams), route, wasPush };
75+
return {
76+
url,
77+
path,
78+
query: Object.fromEntries(u.searchParams),
79+
route: (url, replace) => route({ url, replace }),
80+
wasPush
81+
};
7382
}, [url]);
7483

7584
useLayoutEffect(() => {

test/router.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,4 +504,32 @@ describe('Router', () => {
504504
await sleep(20);
505505
expect(params).toMatchObject({ id: 'bar' });
506506
});
507+
508+
it('should replace the current URL', async () => {
509+
const pushState = jest.spyOn(history, 'pushState');
510+
const replaceState = jest.spyOn(history, 'replaceState');
511+
let loc;
512+
513+
render(
514+
html`
515+
<${LocationProvider}>
516+
<${Router}>
517+
<${Route} path="/foo" component=${() => null} />
518+
<//>
519+
<${() => {
520+
loc = useLocation();
521+
}} />
522+
<//>
523+
`,
524+
scratch
525+
);
526+
527+
await sleep(20);
528+
loc.route("/foo", true);
529+
expect(pushState).not.toHaveBeenCalled();
530+
expect(replaceState).toHaveBeenCalledWith(null, "", "/foo");
531+
532+
pushState.mockRestore();
533+
replaceState.mockRestore();
534+
});
507535
});

0 commit comments

Comments
 (0)