wmr icon indicating copy to clipboard operation
wmr copied to clipboard

[iso] Add async onBeforeRoute() prop hook

Open developit opened this issue 4 years ago â€ĸ 2 comments

This implements <Router onBeforeRoute={async url => {}}>. When onBeforeRoute returns a Promise for a given URL transition, that Promise is thrown from within the incoming route to simulate a Suspense-based paused transition. This means each router maintains its own onBeforeRoute "locking" state.

Here's an example that uses onBeforeRoute to fetch metadata before rendering any routes:

import { useCallback, useEffect } from 'preact/hooks';
import { LocationProvider, Router, hydrate } from 'preact-iso';

function App() {
  const [meta, setMeta] = useState({});
  const loadMeta = useCallback(async url => {
    const res = await fetch(`${url}.json`);
    setMeta(await res.json());
  }, []);
  useEffect(() => {
    document.title = meta.title;
  }, [meta.title]);
  return (
    <LocationProvider>
      <Router onBeforeRoute={loadMeta}>
        <Home path="/" meta={meta} />
        <About path="/about" meta={meta} />
      </Router>
    </LocationProvider>
  );
}

hydrate(<App />);

Demo: https://glitch.com/edit/#!/plausible-satin-rat?path=public%2Fapp.js%3A44%3A5

developit avatar Oct 14 '21 15:10 developit

âš ī¸ No Changeset found

Latest commit: bdc12167da3c229aa1b46bc9b44468746edbf75b

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

changeset-bot[bot] avatar Oct 14 '21 15:10 changeset-bot[bot]

Size Change: +188 B (+3%)

Total Size: 6.5 kB

Filename Size Change
packages/preact-iso/.dist/index.********.js 1.78 kB +70 B (+4%)
packages/preact-iso/.dist/prerender.********.js 348 B -1 B (0%)
packages/preact-iso/router.js 2.66 kB +119 B (+5%) 🔍
â„šī¸ View Unchanged
Filename Size
packages/preact-iso/hydrate.js 290 B
packages/preact-iso/index.js 195 B
packages/preact-iso/lazy.js 594 B
packages/preact-iso/prerender.js 629 B

compressed-size-action

github-actions[bot] avatar Oct 14 '21 16:10 github-actions[bot]