From 8eb538ff8f4ef005fbd9d635bf6ddb0447084606 Mon Sep 17 00:00:00 2001 From: Shahed Nasser Date: Mon, 5 Aug 2024 13:20:34 +0300 Subject: [PATCH] docs: added a section on sending requests to api routes in admin (#8412) --- .../advanced-development/admin/tips/page.mdx | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/www/apps/book/app/advanced-development/admin/tips/page.mdx b/www/apps/book/app/advanced-development/admin/tips/page.mdx index 511fb4f9dd..3b1ef9f717 100644 --- a/www/apps/book/app/advanced-development/admin/tips/page.mdx +++ b/www/apps/book/app/advanced-development/admin/tips/page.mdx @@ -6,6 +6,59 @@ export const metadata = { In this chapter, you'll find some tips for your admin development. +## Send Requests to API Routes + +To send a request to an API route in the Medusa Application, use the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). + +For example: + +export const fetchHighlights = [ + ["14", "fetch", "Send a request to the `/admin/products` API route."] +] + +```tsx title="src/admin/widgets/product-widget.tsx" highlights={fetchHighlights} +import { defineWidgetConfig } from "@medusajs/admin-shared" +import { Container } from "@medusajs/ui" +import { useEffect, useState } from "react" + +const ProductWidget = () => { + const [productsCount, setProductsCount] = useState(0) + const [loading, setLoading] = useState(true) + + useEffect(() => { + if (!loading) { + return + } + + fetch(`/admin/products`, { + credentials: "include" + }) + .then((res) => res.json()) + .then(({ count }) => { + setProductsCount(count) + setLoading(false) + }) + }, [loading]) + + return ( + + {loading && Loading...} + {!loading && You have {productsCount} Product(s).} + + ) +} + +export const config = defineWidgetConfig({ + zone: "product.list.before", +}) + +export default ProductWidget +``` + +In this example, you send a request to the [List Products API route](!api!/admin#products_getproducts) and show the count of products in a widget. + +--- + ## Routing Functionalities To navigate or link to other pages, or perform other routing functionalities, use the [react-router-dom](https://reactrouter.com/en/main) package. It's installed in your project through the Medusa Admin.