Retrieving Data
Let's implement https://example.com/product/abc123 so that we can retrieve the details of a product.
File Layout
The first step is to structure the directories and files so that we can create the /product/abc123 route.
──src/
└─routes/
└─product/
└─[skuId]/
└─index.tsx # https://example.com/product/1234
Implement onGet
In a "page", an onGet function retrieves data (typically from a database, or other stores). The retrieved data can be returned directly as JSON (Accept: application/json) or used as an input to the component to render HTML (Accept: text/html). The onGet function receives the params to extract the parameters used to do data lookup.
In this example, the onGet function returns the product data that is used inside of our component with the useEndpoint() function.
// File: src/routes/product/[skuId]/details/index.tsx
import type { RequestHandler } from '@builder.io/qwik-city';
interface ProductData {
skuId: string;
price: number;
description: string;
}
export const onGet: RequestHandler<ProductData> = async ({ params }) => {
// put your DB access here, we are hard coding a response for simplicity.
return {
skuId: params.skuId,
price: 123.45,
description: `Description for ${params.skuId}`,
};
};
Using onGet in a Component
An onGet function retrieves data and makes it available to the component using useEndpoint().
import { Resource, component$, useStore } from '@builder.io/qwik';
import type { RequestHandler } from '@builder.io/qwik-city';
import { useEndpoint } from "@builder.io/qwik-city";
interface ProductData { ... }
export const onGet: RequestHandler<ProductData> = async ({ params }) => { ... };
export default component$(() => {
const productData = useEndpoint<ProductData>();
return (
<Resource
value={productData}
onPending={() => <div>Loading...</div>}
onRejected={() => <div>Error</div>}
onResolved={(product) => (
<>
<h1>Product: {product.skuId}</h1>
<p>Price: {product.price}</p>
<p>{product.description}</p>
</>
)}
/>
);
});
- Notice that the data request handler and the component are defined in the same file. The data is serviced by the
onGetfunction and the component is by the modules default export. - The component uses
useEndpoint()function to retrieve the data. TheuseEndpoint()function invokesonGetfunction directly on the server but usingfetch()on the client. Your component does not need to think about server/client differences when using data. TheuseEndpoint()function returns an object of typeResourceReturn. AResourceis a promise-like object that can be serialized by Qwik. - The
onGetfunction is invoked before the component. This allows theonGetto return 404 or redirect in case the data is not available. - Notice the use of
<Resource>JSX element. The purpose ofResourceis to allow the client to render different states of theuseEndpoint()resource. - On the server the
<Resource>element will pause rendering until theResourceis resolved or rejected. This is because we don't want the server to renderloading.... (The server needs to know when the component is ready for serialization into HTML.) - You may use
typeof onGetto keep youronGetfunction anduseEndpoint()types in sync. TypeScript is smart enough to determine the types for you.
All of the above is done to abstract the data access from the component in a way that results in correct behavior on both the server and the client.