www: add docs for async route components (#1475)
This commit is contained in:
@@ -88,3 +88,57 @@ export default function Page(props: PageProps) {
|
||||
return <div>You are on the page '{props.url.href}'.</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## Async route components
|
||||
|
||||
Having a separate route handler and component function is nice, when you want to
|
||||
test these in isolation, but can become a bit cumbersome to maintain. They
|
||||
require some additional indirection of declaring an interface for the component
|
||||
`Data` when you're passing it around through `ctx.render()`.
|
||||
|
||||
```tsx
|
||||
interface Data {
|
||||
foo: number;
|
||||
}
|
||||
|
||||
export const handler: Handlers<Data> = {
|
||||
async GET(req, ctx) {
|
||||
const value = await loadFooValue();
|
||||
ctx.render({ foo: value });
|
||||
},
|
||||
};
|
||||
|
||||
export default function MyPage(props: PageProps<Data>) {
|
||||
return <p>foo is: {props.data.foo}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
When a route has both a component and a `GET` handler, they are typically very
|
||||
closely coupled. With async route components you can merge the two together and
|
||||
avoid having to create the `Data` interface boilerplate.
|
||||
|
||||
```tsx
|
||||
// Async route component
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
The code gets a little shorter with async route components. Conceptually, you
|
||||
can think of async route components inlining the `GET` handler into the
|
||||
component function. Note, that you can still add additional HTTP handlers in the
|
||||
same file like before.
|
||||
|
||||
```tsx
|
||||
export const handler: Handlers = {
|
||||
async POST(req) {
|
||||
// ... do something here
|
||||
},
|
||||
};
|
||||
|
||||
export default async function MyPage(req: Request, ctx: RouteContext) {
|
||||
const value = await loadFooValue();
|
||||
return <p>foo is: {value}</p>;
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user