Astro
A recipe list rendered by Astro. The page fetches the recipes in its frontmatter and passes the dehydrated response to a React island, so the HTML already contains the list and the island's hooks start with the same data. Ingredients load in the browser when you open a recipe.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
import { Hydrate, type HydrateProps, useFetch } from "@hyper-fetch/react";
import { useState } from "react";
import { client, getRecipe, popularRecipes } from "../lib/api";
const Ingredients = ({ recipeId }: { recipeId: number }) => {
// Not part of the server render: this request starts in the browser when you open a recipe.
const { data, error, loading } = useFetch(
// `select` is a dummyjson query param: the API returns only these fields.
getRecipe.setParams({ recipeId }).setQueryParams({ select: "ingredients" }),
);
if (loading && !data) return <p aria-busy="true">Loading ingredients in the browser...</p>;
if (error || !data) return <p className="error">Could not load the ingredients.</p>;
return <p className="muted">{data.ingredients.join(", ")}</p>;
};
const RecipeList = () => {
const [opened, setOpened] = useState<number | null>(null);
// The first render already has the server data: no loading state and, while it is fresh, no request.
const { data, error, loading, refetch } = useFetch(popularRecipes, {
revalidate: false,
});
if (loading && !data) return <p aria-busy="true">Loading recipes...</p>;
if (error || !data) return <p className="error">Could not load recipes.</p>;
return (
<>
<header className="toolbar muted">
<span>{data.recipes.length} recipes, rendered by Astro</span>
<button type="button" className="outline secondary" onClick={refetch} disabled={loading}>
Refetch in the browser
</button>
</header>
{data.recipes.map((recipe) => (
<article key={recipe.id}>
<strong>{recipe.name}</strong>
<br />
<small className="muted">
{recipe.cuisine} · {recipe.difficulty} · {recipe.prepTimeMinutes} min
</small>
<details open={opened === recipe.id} onToggle={(event) => event.currentTarget.open && setOpened(recipe.id)}>
<summary>Ingredients</summary>
{opened === recipe.id && <Ingredients recipeId={recipe.id} />}
</details>
</article>
))}
</>
);
};
/** The island: `Hydrate` writes the response from the Astro page into the client cache before the hooks mount. */
export const Recipes = ({ hydration }: { hydration: HydrateProps["data"] }) => (
<Hydrate client={client} data={hydration}>
<RecipeList />
</Hydrate>
);
npx tiged BetterTyped/hyper-fetch/examples/astro/ssr hyper-fetch-astro-ssr && cd hyper-fetch-astro-ssr && npm install && npm run dev- Astro frontmatter sends the request with
send()on the server and packs it withdehydrate(). - An island prop carries the dehydrated response into the browser. Astro serializes it into the HTML.
Hydrateputs the response into the client cache before the island's hooks mount.- Client-only requests still work as usual inside the island.
How it works
-
src/lib/api.tscreates one client and exportspopularRecipes, a request with its query params set. The Astro page and the island import the same request, so they build the same cache key. -
src/pages/index.astroawaits the request in the frontmatter and renders the island withclient:load:---const response = await popularRecipes.send();const hydration = response.success ? [popularRecipes.dehydrate({ response })] : [];---<Recipes client:load hydration={hydration} />A failed response is left out, and the island fetches the recipes in the browser instead.
-
astro.config.mjsadds the React integration. Astro rendersRecipesto HTML on the server and hydrates it in the browser with the same props. -
Recipeswraps the list in<Hydrate client={client} data={hydration}>.RecipeListcallsuseFetch(popularRecipes, { revalidate: false }), renders the recipes on its first render and sends no request. "Refetch in the browser" shows that the hook is live after hydration. -
Ingredientsis not part of the server render. Opening a recipe mounts it, and itsuseFetchfetches the ingredients in the browser. -
The frontmatter runs on every request in
astro dev.astro buildrenders the page once and fetches at build time. To fetch on every request in production, add a server adapter such as@astrojs/nodeand setoutput: "server"; the page code stays the same.
- Content sites built with Astro that have a few interactive React parts reading API data.
- Pages that must ship the data in the HTML, while the island keeps caching and refetching in the browser.
Related
The Astro page sends the request and passes dehydrate() to a React island as a prop. Hydrate unpacks it into the
client cache, so the island renders the server data at once and keeps working like any HyperFetch app.
