Componente Suspense

Mostra una UI fallback mentre componenti asincroni stanno caricando.


Scopo

Suspense renderizza un fallback mentre uno o piu figli aspettano lavoro asincrono. Usalo con:

  • componenti che chiamano useAsync;
  • componenti caricati con lazy;
  • boundary SSR streaming che devono mostrare un fallback prima del contenuto risolto.

Uso

Il componente riceve una prop obbligatoria: fallback. Il fallback deve essere un template html.

import { Suspense, html } from 'wompo';

function Page() {
  return html`
    <${Suspense} fallback=${html`<p>Loading...</p>`}>
      <${AsyncPanel} />
    </${Suspense}>
  `;
}

Con useAsync

Ogni figlio dentro il boundary puo' attivare lo stesso fallback.

function UserCard({ userId }) {
  const user = useAsync(() => fetchUser(userId), [userId]);

  return html`
    <article>
      ${user ? user.name : 'Loading...'}
    </article>
  `;
}

function TeamPage() {
  return html`
    <${Suspense} fallback=${html`<p>Caricamento team...</p>`}>
      <${UserCard} userId="ada" />
      <${UserCard} userId="grace" />
    </${Suspense}>
  `;
}


Con lazy

Suspense funziona anche mentre un componente lazy viene importato.

import { Suspense, html, lazy } from 'wompo';

const LazyComponent = lazy(() => import('./LazyComponent.js'));

function App() {
  return html`
    <p>Questo contenuto e' statico.</p>
    <${Suspense} fallback=${html`<i>Loading...</i>`}>
      <${LazyComponent}>I should be blue...</${LazyComponent}>
    </${Suspense}>
  `;
}

In streaming SSR, un boundary Suspense pendente invia prima il fallback. Quando il lavoro asincrono termina, Wompo invia il contenuto risolto e lo sostituisce nel boundary.