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>
);
}
```
@@ -64,3 +64,7 @@ export const handler: Handlers = {
},
};
```
Handlers can do much more, including fetching data from a database or external
API and passing it to their route. See [Data fetching](/docs/concepts/) for more
details.
@@ -1,55 +0,0 @@
---
description: |
Fetch data for routes dynamically by creating a custom handler and passing
data to the render function.
---
All of the pages in the demo project so far have not used any dynamic data
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
user data from an API or database.
In order to fetch data, the route component must be asynchronous. The first
parameter contains the client's
[`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object.
The second `ctx` parameter is used to get the route parameters.
Here is an example of a route that fetches user data from the GitHub API and
renders it in a page component.
```tsx routes/github/[username].tsx
import { RouteContext } from "$fresh/server.ts";
interface GitHubResponse {
login: string;
name: string;
avatar_url: string;
}
export default async function Page(_req: Request, ctx: RouteContext) {
const resp = await fetch(
`https://api.github.com/users/${ctx.params.username}`,
);
if (!resp.ok) {
return <h1>An Error occurred</h1>;
}
const { login, name, avatar_url } = (await resp.json()) as GitHubResponse;
return (
<div>
<img src={avatar_url} width={64} height={64} />
<h1>{name}</h1>
<p>{login}</p>
</div>
);
}
```
The data is first fetched inside our page component. We check that the response
is returned successfully, by checking whether the
[`ok`](https://developer.mozilla.org/en-US/docs/Web/API/Response/ok) property is
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."
-2
View File
@@ -34,7 +34,6 @@ const toc: RawTableOfContents = {
["create-a-route", "Create a route", "link:latest"],
["dynamic-routes", "Dynamic routes", "link:latest"],
["custom-handlers", "Custom handlers", "link:latest"],
["fetching-data", "Fetching data", "link:latest"],
["form-submissions", "Form submissions", "link:latest"],
["adding-interactivity", "Adding interactivity", "link:latest"],
["deploy-to-production", "Deploy to production", "link:latest"],
@@ -116,7 +115,6 @@ const toc: RawTableOfContents = {
["create-a-route", "Create a route"],
["dynamic-routes", "Dynamic routes"],
["custom-handlers", "Custom handlers"],
["fetching-data", "Fetching data"],
["form-submissions", "Form submissions"],
["adding-interactivity", "Adding interactivity"],
["deploy-to-production", "Deploy to production"],
+2
View File
@@ -8,6 +8,7 @@ import * as $_app from "./routes/_app.tsx";
import * as $_middleware from "./routes/_middleware.ts";
import * as $components from "./routes/components.tsx";
import * as $docs_slug_ from "./routes/docs/[...slug].tsx";
import * as $docs_middleware from "./routes/docs/_middleware.ts";
import * as $docs_index from "./routes/docs/index.tsx";
import * as $index from "./routes/index.tsx";
import * as $raw from "./routes/raw.ts";
@@ -30,6 +31,7 @@ const manifest = {
"./routes/_middleware.ts": $_middleware,
"./routes/components.tsx": $components,
"./routes/docs/[...slug].tsx": $docs_slug_,
"./routes/docs/_middleware.ts": $docs_middleware,
"./routes/docs/index.tsx": $docs_index,
"./routes/index.tsx": $index,
"./routes/raw.ts": $raw,
+23
View File
@@ -0,0 +1,23 @@
import { FreshContext } from "$fresh/server.ts";
const REDIRECTS: Record<string, string> = {
"/docs/getting-started/fetching-data":
"/docs/getting-started/custom-handlers",
};
export async function handler(
_req: Request,
ctx: FreshContext,
) {
// Redirect from old doc URLs to new ones
const redirect = REDIRECTS[ctx.url.pathname];
if (redirect) {
const url = new URL(redirect, ctx.url.origin);
return new Response("", {
status: 307,
headers: { location: url.href },
});
}
return await ctx.next();
}