Skip to content

Commit 51426fa

Browse files
committed
try solution with a state rather than a ref
1 parent d718c8e commit 51426fa

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 } from 'preact/hooks';
2+
import { useContext, useMemo, useReducer, useLayoutEffect, useRef, useState } from 'preact/hooks';
33

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

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

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

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

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;
145144

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

152151
// Successful route transition: un-suspend after a tick and stop rendering the old route:
153152
prev.current = null;
154-
RESOLVED.then(update);
153+
RESOLVED.then(function() {
154+
setIsLoading(false);
155+
});
155156
});
156157
};
157158

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

179180
// The route is loaded and rendered.
180181
if (wasPush) scrollTo(0, 0);
181-
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
182-
isLoading.current = false;
183-
});
182+
if (props.onLoadEnd) props.onLoadEnd(url);
183+
}, [isLoading]);
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)