When to use async in routes and when not? #1712
-
The chapter Async route components in the fresh docs confuses me. According to it, an However, in my tests, For example, if I rewrite the form submissions example ... import { Handlers, PageProps } from "$fresh/server.ts";
const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
interface Data {
results: string[];
query: string;
}
export const handler: Handlers<Data> = {
GET(req, ctx) {
const url = new URL(req.url);
const query = url.searchParams.get("q") || "";
const results = NAMES.filter((name) => name.includes(query));
return ctx.render({ results, query });
},
};
export default function Page({ data }: PageProps<Data>) {
const { results, query } = data;
return (
// ... the jsx ...
);
} ... to ... const NAMES = ["Alice", "Bob", "Charlie", "Dave", "Eve", "Frank"];
export default function Page(req: Request) { // notice, it is not async
const url = new URL(req.url);
const query = url.searchParams.get("q") || "";
const results = NAMES.filter((name) => name.includes(query));
return (
// ... the jsx ...
);
} ... then it still works. So, is using async not necessary? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Synchronous components are bog standard Preact components. Because of that they do not receive // Sync route components receives props, NOT a Request instance
export default function Page(props: PageProps) {
// The `props.url` property is already a `URL` instance,
// because it's not a `Request` object, rather an object created by us.
// So this line does basically `new URL(new URL(...))` which works too
const url = new URL(props.url);
const query = url.searchParams.get("q") || "";
const results = NAMES.filter((name) => name.includes(query));
// ...snip
} So yes, that works. All route components have access to the request URL. If you only need to operate on that and don't need to to anything asynchronous, it's perfectly fine to use a standard Preact component. No need for async routes in this case. Where it gets tricky though, and I guess where your confusion comes from, is that you typed Besides the ability to do
What do you mean by "not possible"? |
Beta Was this translation helpful? Give feedback.
Synchronous components are bog standard Preact components. Because of that they do not receive
Request
as an argument to the function, but rather a standardprops
object. This is typed asPageProps
like in your first snippet. That in turn receives the request url viaprops.url
, which makes your example accidentally work, even though you mistypedprops
as beingRequest
. Both have aurl
property. What's really happening is this here: