Skip to content

Commit 166b7a3

Browse files
committed
try alternative
1 parent e0e05f8 commit 166b7a3

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

router.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { h, createContext, cloneElement, toChildArray } from 'preact';
2-
import { useContext, useMemo, useReducer, useLayoutEffect, useRef, useState } from 'preact/hooks';
2+
import { useContext, useMemo, useReducer, useLayoutEffect, useRef } from 'preact/hooks';
33

44
let push;
55
const UPDATE = (state, url) => {
@@ -89,11 +89,12 @@ export function LocationProvider(props) {
8989
const RESOLVED = Promise.resolve();
9090

9191
export function Router(props) {
92-
const [isLoading, setIsLoading] = useState(false);
92+
const [c, update] = useReducer(c => c + 1, 0);
9393

9494
const { url, query, wasPush, path } = useLocation();
9595
const { rest = path, params = {} } = useContext(RouteContext);
9696

97+
const isLoading = useRef(false);
9798
// Monotonic counter used to check if an un-suspending route is still the current route:
9899
const count = useRef(0);
99100
// The current route:
@@ -138,9 +139,9 @@ export function Router(props) {
138139
// The new route suspended, so keep the previous route around while it loads:
139140
prev.current = p;
140141

141-
setIsLoading(true);
142142
// Fire an event saying we're waiting for the route:
143143
if (props.onLoadStart) props.onLoadStart(url);
144+
isLoading.current = true;
144145

145146
// Re-render on unsuspend:
146147
let c = count.current;
@@ -150,9 +151,7 @@ export function Router(props) {
150151

151152
// Successful route transition: un-suspend after a tick and stop rendering the old route:
152153
prev.current = null;
153-
RESOLVED.then(() => {
154-
setIsLoading(false);
155-
});
154+
RESOLVED.then(update);
156155
});
157156
};
158157

@@ -179,8 +178,9 @@ export function Router(props) {
179178

180179
// The route is loaded and rendered.
181180
if (wasPush) scrollTo(0, 0);
182-
if (props.onLoadEnd) props.onLoadEnd(url);
183-
}, [isLoading]);
181+
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
182+
isLoading.current = false;
183+
}, [c]);
184184

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

0 commit comments

Comments
 (0)