|
1
|
import { Prerequisites } from "docs-ui" |
|
2
|
|
|
3
|
export const metadata = { |
|
4
|
title: `${pageNumber} Create Brands UI Route in Admin`, |
|
5
|
} |
|
6
|
|
|
7
|
# {metadata.title} |
|
8
|
|
|
9
|
In this chapter, you'll add a UI route to the admin dashboard that shows all [brands](../../custom-features/module/page.mdx) in a new page. You'll retrieve the brands from the server and display them in a table with pagination. |
|
10
|
|
|
11
|
<Prerequisites |
|
12
|
items={[ |
|
13
|
{ |
|
14
|
text: "Brands Module", |
|
15
|
link: "/learn/customization/custom-features/module" |
|
16
|
}, |
|
17
|
]} |
|
18
|
/> |
|
19
|
|
|
20
|
## 1. Get Brands API Route |
|
21
|
|
|
22
|
In a [previous chapter](../../extend-features/query-linked-records/page.mdx), you learned how to add an API route that retrieves brands and their products using [Query](../../../fundamentals/query/page.mdx). You'll expand that API route to support pagination, so that on the admin dashboard you can show the brands in a paginated table. |
|
23
|
|
|
24
|
Replace or create the `GET` API route at `src/api/admin/brands/route.ts` with the following: |
|
25
|
|
|
26
|
export const apiRouteHighlights = [ |
|
27
|
["20", "metadata", "Pagination details, such as the total count or how many items were skipped."], |
|
28
|
["23", "queryConfig", "Query configurations parsed from the request."], |
|
29
|
] |
|
30
|
|
|
31
|
```ts title="src/api/admin/brands/route.ts" highlights={apiRouteHighlights} |
|
32
|
// other imports... |
|
33
|
import { |
|
34
|
MedusaRequest, |
|
35
|
MedusaResponse, |
|
36
|
} from "@medusajs/framework/http" |
|
37
|
import { |
|
38
|
ContainerRegistrationKeys, |
|
39
|
} from "@medusajs/framework/utils" |
|
40
|
|
|
41
|
export const GET = async ( |
|
42
|
req: MedusaRequest, |
|
43
|
res: MedusaResponse |
|
44
|
) => { |
|
45
|
const query = req.scope.resolve( |
|
46
|
ContainerRegistrationKeys.QUERY |
|
47
|
) |
|
48
|
|
|
49
|
const { |
|
50
|
data: brands, |
|
51
|
metadata: { count, take, skip } = {}, |
|
52
|
} = await query.graph({ |
|
53
|
entity: "brand", |
|
54
|
...req.queryConfig, |
|
55
|
}) |
|
56
|
|
|
57
|
res.json({ |
|
58
|
brands, |
|
59
|
count, |
|
60
|
limit: take, |
|
61
|
offset: skip, |
|
62
|
}) |
|
63
|
} |
|
64
|
``` |
|
65
|
|
|
66
|
In the API route, you use Query's `graph` method to retrieve the brands. In the method's object parameter, you spread the `queryConfig` property of the request object. This property holds configurations for pagination and retrieved fields. |
|
67
|
|
|
68
|
The query configurations are combined from default configurations, which you'll add next, and the request's query parameters: |
|
69
|
|
|
70
|
- `fields`: The fields to retrieve in the brands. |
|
71
|
- `limit`: The maximum number of items to retrieve. |
|
72
|
- `offset`: The number of items to skip before retrieving the returned items. |
|
73
|
|
|
74
|
When you pass pagination configurations to the `graph` method, the returned object has the pagination's details in a `metadata` property, whose value is an object having the following properties: |
|
75
|
|
|
76
|
- `count`: The total count of items. |
|
77
|
- `take`: The maximum number of items returned in the `data` array. |
|
78
|
- `skip`: The number of items skipped before retrieving the returned items. |
|
79
|
|
|
80
|
You return in the response the retrieved brands and the pagination configurations. |
|
81
|
|
|
82
|
<Note> |
|
83
|
|
|
84
|
Refer to the [Query](../../../fundamentals/query/page.mdx#apply-pagination) chapter to learn more about applying pagination when retrieving linked records. |
|
85
|
|
|
86
|
</Note> |
|
87
|
|
|
88
|
--- |
|
89
|
|
|
90
|
## 2. Add Default Query Configurations |
|
91
|
|
|
92
|
Next, you'll set the default query configurations of the above API route and allow passing query parameters to change the configurations. |
|
93
|
|
|
94
|
Medusa provides a `validateAndTransformQuery` middleware that validates the accepted query parameters for a request and sets the default Query configuration. So, in `src/api/middlewares.ts`, add a new middleware configuration object: |
|
95
|
|
|
96
|
```ts title="src/api/middlewares.ts" |
|
97
|
import { |
|
98
|
defineMiddlewares, |
|
99
|
validateAndTransformQuery, |
|
100
|
} from "@medusajs/framework/http" |
|
101
|
import { createFindParams } from "@medusajs/medusa/api/utils/validators" |
|
102
|
// other imports... |
|
103
|
|
|
104
|
export const GetBrandsSchema = createFindParams() |
|
105
|
|
|
106
|
export default defineMiddlewares({ |
|
107
|
routes: [ |
|
108
|
// ... |
|
109
|
{ |
|
110
|
matcher: "/admin/brands", |
|
111
|
method: "GET", |
|
112
|
middlewares: [ |
|
113
|
validateAndTransformQuery( |
|
114
|
GetBrandsSchema, |
|
115
|
{ |
|
116
|
defaults: [ |
|
117
|
"id", |
|
118
|
"name", |
|
119
|
"products.*", |
|
120
|
], |
|
121
|
isList: true, |
|
122
|
} |
|
123
|
), |
|
124
|
], |
|
125
|
}, |
|
126
|
|
|
127
|
], |
|
128
|
}) |
|
129
|
``` |
|
130
|
|
|
131
|
You apply the `validateAndTransformQuery` middleware on the `GET /admin/brands` API route. The middleware accepts two parameters: |
|
132
|
|
|
133
|
- A [Zod](https://zod.dev/) schema that a request's query parameters must satisfy. Medusa provides `createFindParams` that generates a Zod schema with the following properties: |
|
134
|
- `fields`: A comma-separated string indicating the fields to retrieve. |
|
135
|
- `limit`: The maximum number of items to retrieve. |
|
136
|
- `offset`: The number of items to skip before retrieving the returned items. |
|
137
|
- `order`: The name of the field to sort the items by. Learn more about sorting in [the API reference](!api!/admin#sort-order) |
|
138
|
- An object of Query configurations having the following properties: |
|
139
|
- `defaults`: An array of default fields and relations to retrieve. |
|
140
|
- `isList`: Whether the API route returns a list of items. |
|
141
|
|
|
142
|
By applying the above middleware, you can pass pagination configurations to `GET /admin/brands`, which will return a paginated list of brands. You'll see how it works when you create the UI route. |
|
143
|
|
|
144
|
<Note> |
|
145
|
|
|
146
|
Refer to the [Query](../../../fundamentals/query/page.mdx#request-query-configurations) chapter to learn more about using the `validateAndTransformQuery` middleware to configure Query. |
|
147
|
|
|
148
|
</Note> |
|
149
|
|
|
150
|
--- |
|
151
|
|
|
152
|
## 3. Initialize JS SDK |
|
153
|
|
|
154
|
In your custom UI route, you'll retrieve the brands by sending a request to the Medusa server. Medusa has a [JS SDK](!resources!/js-sdk) that simplifies sending requests to the core API route. |
|
155
|
|
|
156
|
If you didn't follow the [previous chapter](../widget/page.mdx), create the file `src/admin/lib/sdk.ts` with the following content: |
|
157
|
|
|
158
|
 |
|
159
|
|
|
160
|
```ts title="src/admin/lib/sdk.ts" |
|
161
|
import Medusa from "@medusajs/js-sdk" |
|
162
|
|
|
163
|
export const sdk = new Medusa({ |
|
164
|
baseUrl: import.meta.env.VITE_BACKEND_URL || "/", |
|
165
|
debug: import.meta.env.DEV, |
|
166
|
auth: { |
|
167
|
type: "session", |
|
168
|
}, |
|
169
|
}) |
|
170
|
``` |
|
171
|
|
|
172
|
You initialize the SDK passing it the following options: |
|
173
|
|
|
174
|
- `baseUrl`: The URL to the Medusa server. |
|
175
|
- `debug`: Whether to enable logging debug messages. This should only be enabled in development. |
|
176
|
- `auth.type`: The authentication method used in the client application, which is `session` in the Medusa Admin dashboard. |
|
177
|
|
|
178
|
Notice that you use `import.meta.env` to access environment variables in your customizations because the Medusa Admin is built on top of Vite. Learn more in [this chapter](../../../fundamentals/admin/environment-variables/page.mdx). |
|
179
|
|
|
180
|
You can now use the SDK to send requests to the Medusa server. |
|
181
|
|
|
182
|
<Note> |
|
183
|
|
|
184
|
Refer to the [JS SDK Reference](!resources!/js-sdk) to learn more about the it, its options, and how to use it to send requests to Medusa's API routes. |
|
185
|
|
|
186
|
</Note> |
|
187
|
|
|
188
|
--- |
|
189
|
|
|
190
|
## 4. Add a UI Route to Show Brands |
|
191
|
|
|
192
|
You'll now add the UI route that shows the paginated list of brands. A UI route is a React component created in a `page.tsx` file under a sub-directory of `src/admin/routes`. The file's path relative to src/admin/routes determines its path in the dashboard. |
|
193
|
|
|
194
|
<Note> |
|
195
|
|
|
196
|
Refer to the [UI Routes](../../../fundamentals/admin/ui-routes/page.mdx) chapter to learn more about UI routes. |
|
197
|
|
|
198
|
</Note> |
|
199
|
|
|
200
|
So, to add the UI route at the `localhost:9000/app/brands` path, create the file `src/admin/routes/brands/page.tsx` with the following content: |
|
201
|
|
|
202
|
 |
|
203
|
|
|
204
|
export const uiRouteHighlights = [ |
|
205
|
["10", "BrandsPage", "The UI route that displays a new page."], |
|
206
|
["20", "defineRouteConfig", "Export config to add a link for the UI route in the sidebar."], |
|
207
|
["21", "label", "The sidebar item's label."], |
|
208
|
["22", "icon", "The sidebar item's icon."] |
|
209
|
] |
|
210
|
|
|
211
|
```tsx title="src/admin/routes/brands/page.tsx" highlights={uiRouteHighlights} |
|
212
|
import { defineRouteConfig } from "@medusajs/admin-sdk" |
|
213
|
import { TagSolid } from "@medusajs/icons" |
|
214
|
import { |
|
215
|
Container, |
|
216
|
} from "@medusajs/ui" |
|
217
|
import { useQuery } from "@tanstack/react-query" |
|
218
|
import { sdk } from "../../lib/sdk" |
|
219
|
import { useMemo, useState } from "react" |
|
220
|
|
|
221
|
const BrandsPage = () => { |
|
222
|
// TODO retrieve brands |
|
223
|
|
|
224
|
return ( |
|
225
|
<Container className="divide-y p-0"> |
|
226
|
{/* TODO show brands */} |
|
227
|
</Container> |
|
228
|
) |
|
229
|
} |
|
230
|
|
|
231
|
export const config = defineRouteConfig({ |
|
232
|
label: "Brands", |
|
233
|
icon: TagSolid, |
|
234
|
}) |
|
235
|
|
|
236
|
export default BrandsPage |
|
237
|
``` |
|
238
|
|
|
239
|
A route's file must export the React component that will be rendered in the new page. It must be the default export of the file. You can also export configurations that add a link in the sidebar for the UI route. You create these configurations using `defineRouteConfig` from the Admin Extension SDK. |
|
240
|
|
|
241
|
So far, you only show a container. In admin customizations, use components from the [Medusa UI package](!ui!) to maintain a consistent user interface and design in the dashboard. |
|
242
|
|
|
243
|
### Retrieve Brands From API Route |
|
244
|
|
|
245
|
You'll now update the UI route to retrieve the brands from the API route you added earlier. |
|
246
|
|
|
247
|
First, add the following type in `src/admin/routes/brands/page.tsx`: |
|
248
|
|
|
249
|
```tsx title="src/admin/routes/brands/page.tsx" |
|
250
|
type Brand = { |
|
251
|
id: string |
|
252
|
name: string |
|
253
|
} |
|
254
|
type BrandsResponse = { |
|
255
|
brands: Brand[] |
|
256
|
count: number |
|
257
|
limit: number |
|
258
|
offset: number |
|
259
|
} |
|
260
|
``` |
|
261
|
|
|
262
|
You define the type for a brand, and the type of expected response from the `GET /admin/brands` API route. |
|
263
|
|
|
264
|
To display the brands, you'll use Medusa UI's [DataTable](!ui!/components/data-table) component. So, add the following imports in `src/admin/routes/brands/page.tsx`: |
|
265
|
|
|
266
|
```tsx title="src/admin/routes/brands/page.tsx" |
|
267
|
import { |
|
268
|
// ... |
|
269
|
Heading, |
|
270
|
createDataTableColumnHelper, |
|
271
|
DataTable, |
|
272
|
DataTablePaginationState, |
|
273
|
useDataTable, |
|
274
|
} from "@medusajs/ui" |
|
275
|
``` |
|
276
|
|
|
277
|
You import the `DataTable` component and the following utilities: |
|
278
|
|
|
279
|
- `createDataTableColumnHelper`: A utility to create columns for the data table. |
|
280
|
- `DataTablePaginationState`: A type that holds the pagination state of the data table. |
|
281
|
- `useDataTable`: A hook to initialize and configure the data table. |
|
282
|
|
|
283
|
You also import the `Heading` component to show a heading above the data table. |
|
284
|
|
|
285
|
Next, you'll define the table's columns. Add the following before the `BrandsPage` component: |
|
286
|
|
|
287
|
```tsx title="src/admin/routes/brands/page.tsx" |
|
288
|
const columnHelper = createDataTableColumnHelper<Brand>() |
|
289
|
|
|
290
|
const columns = [ |
|
291
|
columnHelper.accessor("id", { |
|
292
|
header: "ID", |
|
293
|
}), |
|
294
|
columnHelper.accessor("name", { |
|
295
|
header: "Name", |
|
296
|
}), |
|
297
|
] |
|
298
|
``` |
|
299
|
|
|
300
|
You use the `createDataTableColumnHelper` utility to create columns for the data table. You define two columns for the ID and name of the brands. |
|
301
|
|
|
302
|
Then, replace the `// TODO retrieve brands` in the component with the following: |
|
303
|
|
|
304
|
export const queryHighlights = [ |
|
305
|
["1", "limit", "The maximum number of items per page."], |
|
306
|
["2", "pagination", "Define a pagination state to be passed to the data table."], |
|
307
|
["6", "offset", "The number of items to skip before retrieving the page's items."], |
|
308
|
["10", "useQuery", "Retrieve brands using Tanstack Query"], |
|
309
|
["11", "fetch", "Send a request to a custom API route."], |
|
310
|
["11", "`/admin/brands`", "The API route's path."], |
|
311
|
["12", "query", "Query parameters to pass in the request"] |
|
312
|
] |
|
313
|
|
|
314
|
```tsx title="src/admin/routes/brands/page.tsx" highlights={queryHighlights} |
|
315
|
const limit = 15 |
|
316
|
const [pagination, setPagination] = useState<DataTablePaginationState>({ |
|
317
|
pageSize: limit, |
|
318
|
pageIndex: 0, |
|
319
|
}) |
|
320
|
const offset = useMemo(() => { |
|
321
|
return pagination.pageIndex * limit |
|
322
|
}, [pagination]) |
|
323
|
|
|
324
|
const { data, isLoading } = useQuery<BrandsResponse>({ |
|
325
|
queryFn: () => sdk.client.fetch(`/admin/brands`, { |
|
326
|
query: { |
|
327
|
limit, |
|
328
|
offset, |
|
329
|
}, |
|
330
|
}), |
|
331
|
queryKey: [["brands", limit, offset]], |
|
332
|
}) |
|
333
|
|
|
334
|
// TODO configure data table |
|
335
|
``` |
|
336
|
|
|
337
|
To enable pagination in the `DataTable` component, you need to define a state variable of type `DataTablePaginationState`. It's an object having the following properties: |
|
338
|
|
|
339
|
- `pageSize`: The maximum number of items per page. You set it to `15`. |
|
340
|
- `pageIndex`: A zero-based index of the current page of items. |
|
341
|
|
|
342
|
You also define a memoized `offset` value that indicates the number of items to skip before retrieving the current page's items. |
|
343
|
|
|
344
|
Then, you use `useQuery` from [Tanstack (React) Query](https://tanstack.com/query/latest) to query the Medusa server. Tanstack Query provides features like asynchronous state management and optimized caching. |
|
345
|
|
|
346
|
<Note type="warning"> |
|
347
|
|
|
348
|
Do not install Tanstack Query as that will cause unexpected errors in your development. If you prefer installing it for better auto-completion in your code editor, make sure to install `v5.64.2` as a development dependency. |
|
349
|
|
|
350
|
</Note> |
|
351
|
|
|
352
|
In the `queryFn` function that executes the query, you use the JS SDK's `client.fetch` method to send a request to your custom API route. The first parameter is the route's path, and the second is an object of request configuration and data. You pass the query parameters in the `query` property. |
|
353
|
|
|
354
|
This sends a request to the [Get Brands API route](#1-get-brands-api-route), passing the pagination query parameters. Whenever `currentPage` is updated, the `offset` is also updated, which will send a new request to retrieve the brands for the current page. |
|
355
|
|
|
356
|
### Display Brands Table |
|
357
|
|
|
358
|
Finally, you'll display the brands in a data table. Replace the `// TODO configure data table` in the component with the following: |
|
359
|
|
|
360
|
```tsx title="src/admin/routes/brands/page.tsx" |
|
361
|
const table = useDataTable({ |
|
362
|
columns, |
|
363
|
data: data?.brands || [], |
|
364
|
getRowId: (row) => row.id, |
|
365
|
rowCount: data?.count || 0, |
|
366
|
isLoading, |
|
367
|
pagination: { |
|
368
|
state: pagination, |
|
369
|
onPaginationChange: setPagination, |
|
370
|
}, |
|
371
|
}) |
|
372
|
``` |
|
373
|
|
|
374
|
You use the `useDataTable` hook to initialize and configure the data table. It accepts an object with the following properties: |
|
375
|
|
|
376
|
- `columns`: The columns of the data table. You created them using the `createDataTableColumnHelper` utility. |
|
377
|
- `data`: The brands to display in the table. |
|
378
|
- `getRowId`: A function that returns a unique identifier for a row. |
|
379
|
- `rowCount`: The total count of items. This is used to determine the number of pages. |
|
380
|
- `isLoading`: A boolean indicating whether the data is loading. |
|
381
|
- `pagination`: An object to configure pagination. It accepts the following properties: |
|
382
|
- `state`: The pagination state of the data table. |
|
383
|
- `onPaginationChange`: A function to update the pagination state. |
|
384
|
|
|
385
|
Then, replace the `{/* TODO show brands */}` in the return statement with the following: |
|
386
|
|
|
387
|
```tsx title="src/admin/routes/brands/page.tsx" |
|
388
|
<DataTable instance={table}> |
|
389
|
<DataTable.Toolbar className="flex flex-col items-start justify-between gap-2 md:flex-row md:items-center"> |
|
390
|
<Heading>Brands</Heading> |
|
391
|
</DataTable.Toolbar> |
|
392
|
<DataTable.Table /> |
|
393
|
<DataTable.Pagination /> |
|
394
|
</DataTable> |
|
395
|
``` |
|
396
|
|
|
397
|
This renders the data table that shows the brands with pagination. The `DataTable` component accepts the `instance` prop, which is the object returned by the `useDataTable` hook. |
|
398
|
|
|
399
|
--- |
|
400
|
|
|
401
|
## Test it Out |
|
402
|
|
|
403
|
To test out the UI route, start the Medusa application: |
|
404
|
|
|
405
|
```bash npm2yarn |
|
406
|
npm run dev |
|
407
|
``` |
|
408
|
|
|
409
|
Then, open the admin dashboard at `http://localhost:9000/app`. After you log in, you'll find a new "Brands" sidebar item. Click on it to see the brands in your store. You can also go to `http://localhost:9000/app/brands` to see the page. |
|
410
|
|
|
411
|
 |
|
412
|
|
|
413
|
--- |
|
414
|
|
|
415
|
## Summary |
|
416
|
|
|
417
|
By following the previous chapters, you: |
|
418
|
|
|
419
|
- Injected a widget into the product details page to show the product's brand. |
|
420
|
- Created a UI route in the Medusa Admin that shows the list of brands. |
|
421
|
|
|
422
|
--- |
|
423
|
|
|
424
|
## Next Steps: Integrate Third-Party Systems |
|
425
|
|
|
426
|
Your customizations often span across systems, where you need to retrieve data or perform operations in a third-party system. |
|
427
|
|
|
428
|
In the next chapters, you'll learn about the concepts that facilitate integrating third-party systems in your application. You'll integrate a dummy third-party system and sync the brands between it and the Medusa application. |