Skip to content

Commit 20c679c

Browse files
committed
solution with effect deps
1 parent e86f231 commit 20c679c

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

router.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { AnyComponent, FunctionComponent, VNode } from 'preact';
33
export const LocationProvider: FunctionComponent;
44

55
export function Router(props: {
6+
onRouteChange?: (url: string) => void;
67
onLoadEnd?: (url: string) => void;
78
onLoadStart?: (url: string) => void;
89
children?: VNode[];

router.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,14 @@ export function LocationProvider(props) {
8787
}
8888

8989
const RESOLVED = Promise.resolve();
90-
9190
export function Router(props) {
92-
const [, update] = useReducer(c => c + 1, 0);
91+
const [c, update] = useReducer(c => c + 1, 0);
9392

9493
const { url, query, wasPush, path } = useLocation();
9594
const { rest = path, params = {} } = useContext(RouteContext);
9695

9796
const isLoading = useRef(false);
97+
const prevRoute = useRef(path);
9898
// Monotonic counter used to check if an un-suspending route is still the current route:
9999
const count = useRef(0);
100100
// The current route:
@@ -177,10 +177,14 @@ export function Router(props) {
177177
hasEverCommitted.current = true;
178178

179179
// The route is loaded and rendered.
180-
if (wasPush) scrollTo(0, 0);
181-
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
182-
isLoading.current = false;
183-
});
180+
if (prevRoute.current !== path) {
181+
if (wasPush) scrollTo(0, 0);
182+
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
183+
if (props.onRouteChange && !isLoading.current) props.onRouteChange(url);
184+
isLoading.current = false;
185+
prevRoute.current = path;
186+
}
187+
}, [path, wasPush, c]);
184188

185189
// Note: curChildren MUST render first in order to set didSuspend & prev.
186190
return [h(RenderRef, { r: cur }), h(RenderRef, { r: prev })];

0 commit comments

Comments
 (0)