docs: Merge data fetching pages (#1974) (#2107)

Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This commit is contained in:
Casey Ydenberg
2023-12-07 10:50:50 +01:00
committed by GitHub
co-authored by Marvin Hagemeister
parent 2caf798016
commit 25afcae943
6 changed files with 63 additions and 58 deletions
+34 -1
View File
@@ -20,7 +20,9 @@ export const handler: Handlers<Project> = {
async GET(_req, ctx) {
const project = await db.projects.findOne({ id: ctx.params.id });
if (!project) {
return new Response("Project not found", { status: 404 });
return ctx.renderNotFound({
message: "Project does not exist",
});
}
return ctx.render(project);
},
@@ -40,3 +42,34 @@ The type parameter on the `PageProps`, `Handlers`, `Handler`, and `FreshContext`
can be used to enforce a TypeScript type to use for the render data. Fresh
enforces during type checking that the types in all of these fields are
compatible within a single page.
## Asynchronous routes
As a shortcut for combining a `GET` handler with a route, you can define your
route as `async`. An `async` route (a route that returns a promise) will be
called with the `Request` and a `RouteContext` (similar to a `HandlerContext`).
Here is the above example rewritten using this shortcut:
```tsx routes/projects/[id].tsx
interface Project {
name: string;
stars: number;
}
export default async function ProjectPage(_req, ctx: FreshContext) {
const project: Project | null = await db.projects.findOne({
id: ctx.params.id,
});
if (!project) {
return <h1>Project not found</h1>;
}
return (
<div>
<h1>{project.name}</h1>
<p>{project.stars} stars</p>
</div>
);
}
```