diff --git a/docs/canary/concepts/routes.md b/docs/canary/concepts/routes.md index d3c2fa2d..f0487b39 100644 --- a/docs/canary/concepts/routes.md +++ b/docs/canary/concepts/routes.md @@ -88,3 +88,57 @@ export default function Page(props: PageProps) { return
You are on the page '{props.url.href}'.
; } ``` + +## 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 = { + async GET(req, ctx) { + const value = await loadFooValue(); + ctx.render({ foo: value }); + }, +}; + +export default function MyPage(props: PageProps) { + return

foo is: {props.data.foo}

; +} +``` + +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

foo is: {value}

; +} +``` + +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

foo is: {value}

; +} +```