www: rewriting "data fetching" code example (#1603)

Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
This commit is contained in:
Ondřej Tuček
2023-08-08 14:30:37 +02:00
committed by GitHub
co-authored by Asher Gomez
parent 7d4c751105
commit 9b4f7a1ad0
+23 -30
View File
@@ -9,13 +9,10 @@ during rendering. In real projects, this is often different. In many cases you
may need to read a file from disk (e.g. markdown for a blog post), or fetch some may need to read a file from disk (e.g. markdown for a blog post), or fetch some
user data from an API or database. user data from an API or database.
These operations are all asynchronous. Rendering however, is always synchronous. In order to fetch data, the route component must be asynchronous. The first
Instead of fetching data directly during rendering, it should be loaded in a parameter contains the client's
route's `handler` function and then passed to the page component via first [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object.
argument to `ctx.render()`. The second `ctx` parameter is used to get the route parameters.
The data that is passed to `ctx.render()` can then be accessed via the
`props.data` field on the page component.
Here is an example of a route that fetches user data from the GitHub API and Here is an example of a route that fetches user data from the GitHub API and
renders it in a page component. renders it in a page component.
@@ -23,42 +20,38 @@ renders it in a page component.
```tsx ```tsx
// routes/github/[username].tsx // routes/github/[username].tsx
import { Handlers, PageProps } from "$fresh/server.ts"; import { RouteContext } from "$fresh/server.ts";
interface User { interface GitHubResponse {
login: string; login: string;
name: string; name: string;
avatar_url: string; avatar_url: string;
} }
export const handler: Handlers<User | null> = { export default async function Page(_req: Request, ctx: RouteContext) {
async GET(_, ctx) { const resp = await fetch(
const { username } = ctx.params; `https://api.github.com/users/${ctx.params.username}`,
const resp = await fetch(`https://api.github.com/users/${username}`); );
if (resp.status === 404) {
return ctx.render(null);
}
const user: User = await resp.json();
return ctx.render(user);
},
};
export default function Page({ data }: PageProps<User | null>) { if (!resp.ok) {
if (!data) { return <h1>An Error occurred</h1>;
return <h1>User not found</h1>;
} }
const { login, name, avatar_url } = await resp.json() as GitHubResponse;
return ( return (
<div> <div>
<img src={data.avatar_url} width={64} height={64} /> <img src={avatar_url} width={64} height={64} />
<h1>{data.name}</h1> <h1>{name}</h1>
<p>{data.login}</p> <p>{login}</p>
</div> </div>
); );
} }
``` ```
The data is first fetched inside of the handler by making an API call to GitHub. The data is first fetched inside our page component. We check that the response
If the API call succeeds, the data is passed to the page component. If the API is returned successfully, by checking whether the
call fails, the page component is rendered with `null` as the data. The page [`ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok) property is
component grabs the data from the props and renders it. true. If the API call was successful, we will see our div with the user's GitHub
image, name, and username. Otherwise, we should see a heading saying: "An Error
occurred."