Skip to content

Commit

Permalink
try alternative
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Sep 8, 2021
1 parent be67e56 commit dc6d873
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions packages/preact-iso/router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { h, createContext, cloneElement, toChildArray } from 'preact';
import { useContext, useMemo, useReducer, useLayoutEffect, useRef, useState } from 'preact/hooks';
import { useContext, useMemo, useReducer, useLayoutEffect, useRef } from 'preact/hooks';

let push;
const UPDATE = (state, url) => {
Expand Down Expand Up @@ -89,11 +89,12 @@ export function LocationProvider(props) {
const RESOLVED = Promise.resolve();

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

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

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

setIsLoading(true);
// Fire an event saying we're waiting for the route:
if (props.onLoadStart) props.onLoadStart(url);
isLoading.current = true;

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

// Successful route transition: un-suspend after a tick and stop rendering the old route:
prev.current = null;
RESOLVED.then(() => {
setIsLoading(false);
});
RESOLVED.then(update);
});
};

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

// The route is loaded and rendered.
if (wasPush) scrollTo(0, 0);
if (props.onLoadEnd) props.onLoadEnd(url);
}, [isLoading]);
if (props.onLoadEnd && isLoading.current) props.onLoadEnd(url);
isLoading.current = false;
}, [c]);

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

0 comments on commit dc6d873

Please sign in to comment.