1
1
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' ;
3
3
4
4
let push ;
5
5
const UPDATE = ( state , url ) => {
@@ -89,12 +89,11 @@ export function LocationProvider(props) {
89
89
const RESOLVED = Promise . resolve ( ) ;
90
90
91
91
export function Router ( props ) {
92
- const [ , update ] = useReducer ( c => c + 1 , 0 ) ;
92
+ const [ isLoading , setIsLoading ] = useState ( false ) ;
93
93
94
94
const { url, query, wasPush, path } = useLocation ( ) ;
95
95
const { rest = path , params = { } } = useContext ( RouteContext ) ;
96
96
97
- const isLoading = useRef ( false ) ;
98
97
// Monotonic counter used to check if an un-suspending route is still the current route:
99
98
const count = useRef ( 0 ) ;
100
99
// The current route:
@@ -139,9 +138,9 @@ export function Router(props) {
139
138
// The new route suspended, so keep the previous route around while it loads:
140
139
prev . current = p ;
141
140
141
+ setIsLoading ( true ) ;
142
142
// Fire an event saying we're waiting for the route:
143
143
if ( props . onLoadStart ) props . onLoadStart ( url ) ;
144
- isLoading . current = true ;
145
144
146
145
// Re-render on unsuspend:
147
146
let c = count . current ;
@@ -151,7 +150,9 @@ export function Router(props) {
151
150
152
151
// Successful route transition: un-suspend after a tick and stop rendering the old route:
153
152
prev . current = null ;
154
- RESOLVED . then ( update ) ;
153
+ RESOLVED . then ( function ( ) {
154
+ setIsLoading ( false ) ;
155
+ } ) ;
155
156
} ) ;
156
157
} ;
157
158
@@ -178,9 +179,8 @@ export function Router(props) {
178
179
179
180
// The route is loaded and rendered.
180
181
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 ] ) ;
184
184
185
185
// Note: curChildren MUST render first in order to set didSuspend & prev.
186
186
return [ h ( RenderRef , { r : cur } ) , h ( RenderRef , { r : prev } ) ] ;
0 commit comments