Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[iso] Add async onBeforeRoute() prop hook #885

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions packages/preact-iso/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export function Router(props) {
// was the most recent render successful (did not suspend):
const didSuspend = useRef();
didSuspend.current = false;
// current return value of onBeforeRoute() prop
const onBeforeRoute = useRef();

cur.current = useMemo(() => {
// This hack prevents Preact from diffing when we swap `cur` to `prev`:
Expand All @@ -117,6 +119,16 @@ export function Router(props) {

prev.current = cur.current;

let obr = props.onBeforeRoute && props.onBeforeRoute(url);
if (obr && obr.then) {
obr = obr.then(() => {
if (onBeforeRoute.current === obr) {
onBeforeRoute.current = null;
}
});
}
onBeforeRoute.current = obr;

let p, d, m;
toChildArray(props.children).some(vnode => {
const matches = exec(rest, vnode.props.path, (m = { path: rest, query, params, rest: '' }));
Expand Down Expand Up @@ -188,11 +200,14 @@ export function Router(props) {
}, [path, wasPush, c]);

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

// Lazily render a ref's current value:
const RenderRef = ({ r }) => r.current;
const RenderRef = ({ p, r }) => {
if (p && p.then) throw p;
return r.current;
};

Router.Provider = LocationProvider;

Expand Down