1
1
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' ;
3
3
4
4
let push ;
5
5
const UPDATE = ( state , url ) => {
@@ -89,11 +89,12 @@ export function LocationProvider(props) {
89
89
const RESOLVED = Promise . resolve ( ) ;
90
90
91
91
export function Router ( props ) {
92
- const [ isLoading , setIsLoading ] = useState ( false ) ;
92
+ const [ c , update ] = useReducer ( c => c + 1 , 0 ) ;
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 ) ;
97
98
// Monotonic counter used to check if an un-suspending route is still the current route:
98
99
const count = useRef ( 0 ) ;
99
100
// The current route:
@@ -138,9 +139,9 @@ export function Router(props) {
138
139
// The new route suspended, so keep the previous route around while it loads:
139
140
prev . current = p ;
140
141
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 ;
144
145
145
146
// Re-render on unsuspend:
146
147
let c = count . current ;
@@ -150,9 +151,7 @@ export function Router(props) {
150
151
151
152
// Successful route transition: un-suspend after a tick and stop rendering the old route:
152
153
prev . current = null ;
153
- RESOLVED . then ( ( ) => {
154
- setIsLoading ( false ) ;
155
- } ) ;
154
+ RESOLVED . then ( update ) ;
156
155
} ) ;
157
156
} ;
158
157
@@ -179,8 +178,9 @@ export function Router(props) {
179
178
180
179
// The route is loaded and rendered.
181
180
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 ] ) ;
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