From a248bf6e4f4b3d2310dc34820842d9479f7deb27 Mon Sep 17 00:00:00 2001 From: Shahed Nasser Date: Mon, 23 Jan 2023 21:04:09 +0200 Subject: [PATCH] docs: added medusa-react snippets in how-to guides (#3091) * added medusa-react snippets * added more code snippets * added medusa-react snippets * docs: added medusa-react snippets to storefront how-to * docs: added medusa-react snippets in admin how-to * docs: fixed incorrect link --- docs/api/admin-spec3-base.yaml | 13 +- docs/content/advanced/admin/import-prices.mdx | 117 ++++++- .../advanced/admin/import-products.mdx | 117 ++++++- .../advanced/admin/manage-customers.mdx | 98 ++++++ .../advanced/admin/manage-discounts.mdx | 236 +++++++++++++-- .../advanced/admin/manage-gift-cards.mdx | 225 +++++++++++++- .../admin/manage-publishable-api-keys.mdx | 216 ++++++++++++- .../content/advanced/admin/manage-regions.mdx | 162 +++++++++- docs/content/advanced/admin/order-edit.mdx | 218 +++++++++++++- .../advanced/admin/use-customergroups-api.mdx | 253 ++++++++++++++-- .../advanced/backend/price-lists/use-api.mdx | 188 +++++++++++- .../backend/sales-channels/manage-admin.mdx | 285 ++++++++++++++++-- .../advanced/storefront/customer-profiles.mdx | 99 +++++- .../storefront/handle-order-edits.mdx | 109 ++++++- .../how-to-implement-checkout-flow.mdx | 228 +++++++++++++- .../storefront/implement-claim-order.mdx | 38 ++- .../storefront/use-discounts-in-checkout.mdx | 45 ++- .../advanced/storefront/use-gift-cards.mdx | 88 +++++- .../advanced/storefront/use-regions.mdx | 97 +++++- .../storefront/use-sales-channels.mdx | 103 ++++++- docs/content/guides/carts-in-medusa.mdx | 247 +++++++++++++-- docs/content/js-client/overview.md | 2 +- docs/content/medusa-react/overview.md | 17 +- 23 files changed, 3032 insertions(+), 169 deletions(-) diff --git a/docs/api/admin-spec3-base.yaml b/docs/api/admin-spec3-base.yaml index 3253d88df8..89413a84c8 100644 --- a/docs/api/admin-spec3-base.yaml +++ b/docs/api/admin-spec3-base.yaml @@ -286,11 +286,20 @@ components: In this API reference, you'll find in the cURL request samples the use of `{api_token}`. This is where you must pass the API token. - If you're alternatively following along with the JS Client request samples, you must provide the `apiKey` option when creating the Medusa client: + If you're following along with the JS Client request samples, you must provide the `apiKey` option when creating the Medusa client: - ```js + ```ts const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3, apiKey: '{api_token}' }) ``` + + If you're using Medusa React, you can pass the `apiKey` prop to `MedusaProvider`: + + ```tsx + + ``` scheme: bearer cookie_auth: type: apiKey diff --git a/docs/content/advanced/admin/import-prices.mdx b/docs/content/advanced/admin/import-prices.mdx index 3fe74fe75c..8345426968 100644 --- a/docs/content/advanced/admin/import-prices.mdx +++ b/docs/content/advanced/admin/import-prices.mdx @@ -40,10 +40,16 @@ You must have a CSV file that you will use to import prices into your Medusa ser ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -67,17 +73,37 @@ You can do that by sending the following request to the [Upload Files](https://d -```jsx +```ts medusa.admin.uploads.create(file) // file is an instance of File .then(({ uploads }) => { const key = uploads[0].key }) ``` + + + +```tsx +import { useAdminUploadFile } from "medusa-react" + +const ImportPrices = () => { + const uploadFile = useAdminUploadFile() + // ... + + const handleFileUpload = (file: File) => { + uploadFile.mutate(file) + } + + // ... +} + +export default ImportPrices +``` + -```jsx +```ts const formData = new FormData() formData.append("files", file) // file is an instance of File @@ -121,7 +147,7 @@ You can do that by sending the following request to the [Create a Batch Job](htt -```jsx +```ts medusa.admin.batchJobs.create({ type: "price-list-import", context: { @@ -135,10 +161,36 @@ medusa.admin.batchJobs.create({ }) ``` + + + +```tsx +import { useAdminCreateBatchJob } from "medusa-react" + +const ImportPrices = () => { + const createBatchJob = useAdminCreateBatchJob() + // ... + + const handleCreateBatchJob = () => { + createBatchJob.mutate({ + type: "price-list-import", + context: { + fileKey: key, // obtained from previous step + }, + dry_run: true, + }) + } + + // ... +} + +export default ImportPrices +``` + -```jsx +```ts fetch(`/admin/batch-jobs`, { method: "POST", credentials: "include", @@ -209,17 +261,44 @@ You can retrieve all the details of the batch job, including its status and the -```jsx +```ts medusa.admin.batchJobs.retrieve(batchJobId) .then(( batch_job ) => { console.log(batch_job.status, batch_job.result) }) ``` + + + +```tsx +import { useAdminBatchJob } from "medusa-react" + +const ImportPrices = () => { + const { batch_job, isLoading } = useAdminBatchJob(batchJobId) + // ... + + return ( +
+ {/* ... */} + {isLoading && Loading} + {batch_job && ( + + Status: {batch_job.status}. + Number of Prices: {batch_job.result.count} + + )} +
+ ) +} + +export default ImportPrices +``` +
-```jsx +```ts fetch(`/admin/batch-jobs/${batchJobId}`, { credentials: "include", }) @@ -272,17 +351,37 @@ To confirm a batch job send the following request: -```jsx +```ts medusa.admin.batchJobs.confirm(batchJobId) .then(( batch_job ) => { console.log(batch_job.status) }) ``` + + + +```tsx +import { useAdminConfirmBatchJob } from "medusa-react" + +const ImportPrices = () => { + const confirmBatchJob = useAdminConfirmBatchJob(batchJobId) + // ... + + const handleConfirmJob = () => { + confirmBatchJob.mutate() + } + + // ... +} + +export default ImportPrices +``` + -```jsx +```ts fetch(`/admin/batch-jobs/${batchJobId}/confirm`, { method: "POST", credentials: "include", diff --git a/docs/content/advanced/admin/import-products.mdx b/docs/content/advanced/admin/import-products.mdx index ee9074d0ca..8b93dbea5c 100644 --- a/docs/content/advanced/admin/import-products.mdx +++ b/docs/content/advanced/admin/import-products.mdx @@ -40,10 +40,16 @@ If you have Sales Channels enabled on your server, you must use [this CSV exampl ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -61,17 +67,37 @@ You can do that by sending the following request to the [Upload Files](https://d -```jsx +```ts medusa.admin.uploads.create(file) // file is an instance of File .then(({ uploads }) => { const key = uploads[0].key }) ``` + + + +```tsx +import { useAdminUploadFile } from "medusa-react" + +const ImportProducts = () => { + const uploadFile = useAdminUploadFile() + // ... + + const handleFileUpload = (file: File) => { + uploadFile.mutate(file) + } + + // ... +} + +export default ImportProducts +``` + -```jsx +```ts const formData = new FormData() formData.append("files", file) // file is an instance of File @@ -115,7 +141,7 @@ You can do that by sending the following request to the [Create a Batch Job](htt -```jsx +```ts medusa.admin.batchJobs.create({ type: "product-import", context: { @@ -128,10 +154,36 @@ medusa.admin.batchJobs.create({ }) ``` + + + +```tsx +import { useAdminCreateBatchJob } from "medusa-react" + +const ImportProducts = () => { + const createBatchJob = useAdminCreateBatchJob() + // ... + + const handleCreateBatchJob = () => { + createBatchJob.mutate({ + type: "product-import", + context: { + fileKey: key, // obtained from previous step + }, + dry_run: true, + }) + } + + // ... +} + +export default ImportProducts +``` + -```jsx +```ts fetch(`/admin/batch-jobs`, { method: "POST", credentials: "include", @@ -197,17 +249,44 @@ You can retrieve all the details of the batch job, including its status and the -```jsx +```ts medusa.admin.batchJobs.retrieve(batchJobId) .then(( batch_job ) => { console.log(batch_job.status, batch_job.result) }) ``` + + + +```tsx +import { useAdminBatchJob } from "medusa-react" + +const ImportProducts = () => { + const { batch_job, isLoading } = useAdminBatchJob(batchJobId) + // ... + + return ( +
+ {/* ... */} + {isLoading && Loading} + {batch_job && ( + + Status: {batch_job.status}. + Number of Products: {batch_job.result.count} + + )} +
+ ) +} + +export default ImportProducts +``` +
-```jsx +```ts fetch(`/admin/batch-jobs/${batchJobId}`, { credentials: "include", }) @@ -260,17 +339,37 @@ To confirm a batch job send the following request: -```jsx +```ts medusa.admin.batchJobs.confirm(batchJobId) .then(( batch_job ) => { console.log(batch_job.status) }) ``` + + + +```tsx +import { useAdminConfirmBatchJob } from "medusa-react" + +const ImportProducts = () => { + const confirmBatchJob = useAdminConfirmBatchJob(batchJobId) + // ... + + const handleConfirmJob = () => { + confirmBatchJob.mutate() + } + + // ... +} + +export default ImportProducts +``` + -```jsx +```ts fetch(`/admin/batch-jobs/${batchJobId}/confirm`, { method: "POST", credentials: "include", diff --git a/docs/content/advanced/admin/manage-customers.mdx b/docs/content/advanced/admin/manage-customers.mdx index 94b2734b26..de5beedd17 100644 --- a/docs/content/advanced/admin/manage-customers.mdx +++ b/docs/content/advanced/admin/manage-customers.mdx @@ -31,6 +31,12 @@ This guide includes code snippets to send requests to your Medusa server using M If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -53,6 +59,34 @@ medusa.admin.customers.list() }) ``` + + + +```tsx +import { Customer } from "@medusajs/medusa" +import { useAdminCustomers } from "medusa-react" + +const Customers = () => { + const { customers, isLoading } = useAdminCustomers() + + return ( +
+ {isLoading && Loading...} + {customers && !customers.length && No customers} + {customers && customers.length > 0 && ( +
    + {customers.map((customer: Customer) => ( +
  • {customer.first_name}
  • + ))} +
+ )} +
+ ) +} + +export default Customers +``` +
@@ -115,6 +149,38 @@ medusa.admin.customers.create({ }) ``` + + + +```tsx +import { useAdminCreateCustomer } from "medusa-react" + +const CreateCustomer = () => { + const createCustomer = useAdminCreateCustomer() + // ... + + const handleCreate = () => { + // ... + createCustomer.mutate({ + first_name, + last_name, + email, + password, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default CreateCustomer +``` +
@@ -187,6 +253,38 @@ medusa.admin.customers.update(customerId, { }) ``` + + + +```tsx +import { useAdminUpdateCustomer } from "medusa-react" + +const UpdateCustomer = () => { + const updateCustomer = useAdminUpdateCustomer(customerId) + // ... + + const handleUpdate = () => { + // ... + updateCustomer.mutate({ + email, + password, + first_name, + last_name, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default UpdateCustomer +``` +
diff --git a/docs/content/advanced/admin/manage-discounts.mdx b/docs/content/advanced/admin/manage-discounts.mdx index c3a148e7b1..56f72570fc 100644 --- a/docs/content/advanced/admin/manage-discounts.mdx +++ b/docs/content/advanced/admin/manage-discounts.mdx @@ -43,6 +43,12 @@ This guide includes code snippets to send requests to your Medusa server using M If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -58,7 +64,7 @@ You can create a discount by sending a request to the [Create Discount](/api/adm -```jsx +```ts import { AllocationType, DiscountRuleType } from "@medusajs/medusa" // ... medusa.admin.discounts.create({ @@ -69,18 +75,54 @@ medusa.admin.discounts.create({ allocation: AllocationType.ITEM, }, regions: [ - regionId, + regionId, ], + is_dynamic: false, + is_disabled: false, }) .then(({ discount }) => { console.log(discount.id) }) ``` + + + +```tsx +import { useAdminCreateDiscount } from "medusa-react" +import { AllocationType, DiscountRuleType } from "@medusajs/medusa" + +const CreateDiscount = () => { + const createDiscount = useAdminCreateDiscount() + // ... + + const handleCreate = () => { + // ... + createDiscount.mutate({ + code, + rule: { + type: DiscountRuleType.FIXED, + value: 10, + allocation: AllocationType.ITEM, + }, + regions: [ + regionId, + ], + is_dynamic: false, + is_disabled: false, + }) + } + + // ... +} + +export default CreateDiscount +``` + -```jsx +```ts fetch(`/admin/discounts`, { method: "POST", credentials: "include", @@ -97,6 +139,8 @@ fetch(`/admin/discounts`, { regions: [ regionId, ], + is_dynamic: false, + is_disabled: false, }), }) .then((response) => response.json()) @@ -121,7 +165,9 @@ curl -L -X POST '/admin/discounts' \ }, "regions": [ "" - ] + ], + "is_dynamic": false, + "is_disabled": false }' ``` @@ -150,9 +196,8 @@ For example, you can update the discount’s description and status by sending t -```jsx +```ts medusa.admin.discounts.update(discountId, { - description: "New description", is_disabled: true, }) .then(({ discount }) => { @@ -160,10 +205,33 @@ medusa.admin.discounts.update(discountId, { }) ``` + + + +```tsx +import { useAdminUpdateDiscount } from "medusa-react" + +const UpdateDiscount = () => { + const updateDiscount = useAdminUpdateDiscount(discount_id) + // ... + + const handleUpdate = () => { + // ... + updateDiscount.mutate({ + is_disabled: true, + }) + } + + // ... +} + +export default UpdateDiscount +``` + -```jsx +```ts fetch(`/admin/discounts/${discountId}`, { method: "POST", credentials: "include", @@ -171,7 +239,6 @@ fetch(`/admin/discounts/${discountId}`, { "Content-Type": "application/json", }, body: JSON.stringify({ - description: "New description", is_disabled: true, }), }) @@ -189,7 +256,6 @@ curl -L -X POST '/admin/discounts/' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ --data-raw '{ - "description": "New description", "is_disabled": true }' ``` @@ -197,7 +263,7 @@ curl -L -X POST '/admin/discounts/' \ -This request accepts the discount ID as a path parameter. You can pass the parameters you want to update in the request body. In the example above, you pass the `description` and `is_disabled` parameters to update them. +This request accepts the discount ID as a path parameter. You can pass the parameters you want to update in the request body. In the example above, is_disabled` parameter to update it. You can check the [API reference](/api/admin/#tag/Discount/operation/PostDiscountsDiscount) for all the accepted parameters to update the discount. @@ -220,7 +286,7 @@ You can send a request to the [Create Condition](/api/admin/#tag/Discount-Condit -```jsx +```ts import { DiscountConditionOperator } from "@medusajs/medusa" // ... medusa.admin.discounts.createCondition(discount_id, { @@ -234,10 +300,40 @@ medusa.admin.discounts.createCondition(discount_id, { }) ``` + + + +```tsx +import { useAdminDiscountCreateCondition } from "medusa-react" +import { DiscountConditionOperator } from "@medusajs/medusa" + +const Discount = () => { + const createCondition = useAdminDiscountCreateCondition(discount_id) + // ... + + const handleCreateCondition = ( + operator: DiscountConditionOperator, + productId: string + ) => { + // ... + createCondition.mutate({ + operator, + products: [ + productId, + ], + }) + } + + // ... +} + +export default Discount +``` + -```jsx +```ts fetch(`/admin/discounts/${discountId}/conditions`, { method: "POST", credentials: "include", @@ -299,7 +395,7 @@ You can retrieve a condition and its resources by sending a request to the [Get -```jsx +```ts medusa.admin.discounts.getCondition(discountId, conditionId, { expand: "products", }) @@ -308,10 +404,44 @@ medusa.admin.discounts.getCondition(discountId, conditionId, { }) ``` + + + +```tsx +import { useAdminGetDiscountCondition } from "medusa-react" +import { Product } from "@medusajs/medusa" + +const DiscountCondition = () => { + const { discount_condition, isLoading } = useAdminGetDiscountCondition( + discount_id, + conditionId + ) + // ... + + return ( +
+ {isLoading && Loading} + {discount_condition && ( + <> + {discount_condition.id} +
    + {discount_condition.products.map((product: Product) => ( +
  • {product.title}
  • + ))} +
+ + )} +
+ ) +} + +export default DiscountCondition +``` +
-```jsx +```ts fetch( `/admin/discounts/${discountId}` + `/conditions/${conditionId}&expand=products`, @@ -351,7 +481,7 @@ For example, to update the products in a condition: -```jsx +```ts medusa.admin.discounts.updateCondition(discountId, conditionId, { products: [ productId1, @@ -363,10 +493,36 @@ medusa.admin.discounts.updateCondition(discountId, conditionId, { }) ``` + + + +```tsx +import { useAdminDiscountUpdateCondition } from "medusa-react" +import { Product } from "@medusajs/medusa" + +const DiscountCondition = () => { + const updateCondition = useAdminDiscountUpdateCondition( + discount_id, + conditionId + ) + // ... + + const handleUpdateCondition = (productIds: string[]) => { + updateCondition.mutate({ + products: productIds, + }) + } + + // ... +} + +export default DiscountCondition +``` + -```jsx +```ts fetch( `/admin/discounts/${discountId}/conditions/${conditionId}`, { @@ -420,17 +576,37 @@ You can delete a condition by sending a request to the [Delete Condition](/api/a -```jsx +```ts medusa.admin.discounts.deleteCondition(discountId, conditionId) .then(({ discount }) => { console.log(discount) }) ``` + + + +```tsx +import { useAdminDiscountRemoveCondition } from "medusa-react" + +const Discount = () => { + const deleteCondition = useAdminDiscountRemoveCondition(discount_id) + // ... + + const handleUpdateCondition = (conditionId: string) => { + deleteCondition.mutate(conditionId) + } + + // ... +} + +export default Discount +``` + -```jsx +```ts fetch( `/admin/discounts/${discountId}/conditions/${conditionId}`, { @@ -468,17 +644,37 @@ You can delete a discount by sending a request to the [Delete Discount](/api/adm -```jsx +```ts medusa.admin.discounts.delete(discount_id) .then(({ id, object, deleted }) => { console.log(id) }) ``` + + + +```tsx +import { useAdminDeleteDiscount } from "medusa-react" + +const Discount = () => { + const deleteDiscount = useAdminDeleteDiscount(discount_id) + // ... + + const handleDelete = () => { + deleteDiscount.mutate() + } + + // ... +} + +export default Discount +``` + -```jsx +```ts fetch(`/admin/discounts/${discountId}`, { method: "DELETE", credentials: "include", diff --git a/docs/content/advanced/admin/manage-gift-cards.mdx b/docs/content/advanced/admin/manage-gift-cards.mdx index 64437c8114..389ceebe4a 100644 --- a/docs/content/advanced/admin/manage-gift-cards.mdx +++ b/docs/content/advanced/admin/manage-gift-cards.mdx @@ -32,10 +32,16 @@ It is assumed that you already have a Medusa server installed and set up. If not ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -71,6 +77,37 @@ medusa.admin.products.list({ }) ``` + + + +```tsx +import { Product } from "@medusajs/medusa" +import { PricedProduct } from "@medusajs/medusa/dist/types/pricing" +import { useAdminProducts } from "medusa-react" + +const GiftCard = () => { + const { products, isLoading } = useAdminProducts({ + is_giftcard: true, + }) + + return ( +
+ {isLoading && Loading...} + {products && products.length > 0 && ( +
    + {products.map((product: (Product | PricedProduct)) => ( +
  • {product.title}
  • + ))} +
+ )} + {products && !products.length && No Gift Cards} +
+ ) +} + +export default GiftCard +``` +
@@ -149,6 +186,55 @@ medusa.admin.products.create({ }) ``` + + + +```tsx +import { useAdminCreateProduct } from "medusa-react" +import { ProductStatus } from "@medusajs/medusa" + +const CreateGiftCard = () => { + const createGiftCard = useAdminCreateProduct() + // ... + + const handleCreate = () => { + createGiftCard.mutate({ + title: "My Gift Card", + is_giftcard: true, + discountable: false, + status: ProductStatus.PUBLISHED, + options: [ + { + title: "Denomination", + }, + ], + variants: [ + { + title: "1", + inventory_quantity: 0, + manage_inventory: false, + prices: [ + { + amount: 2000, + currency_code: "usd", + }, + ], + options: [ + { + value: "2000", + }, + ], + }, + ], + }) + } + + // ... +} + +export default CreateGiftCard +``` + @@ -266,6 +352,28 @@ medusa.admin.products.update(giftCardId, { }) ``` + + + +```tsx +import { useAdminUpdateProduct } from "medusa-react" + +const UpdateGiftCard = () => { + const createGiftCard = useAdminUpdateProduct(giftCardId) + // ... + + const handleUpdate = () => { + createGiftCard.mutate({ + description: "The best gift card", + }) + } + + // ... +} + +export default UpdateGiftCard +``` + @@ -321,6 +429,26 @@ medusa.admin.products.delete(giftCardId) }) ``` + + + +```tsx +import { useAdminDeleteProduct } from "medusa-react" + +const GiftCard = () => { + const deleteGiftCard = useAdminDeleteProduct(giftCardId) + // ... + + const handleDelete = () => { + deleteGiftCard.mutate() + } + + // ... +} + +export default GiftCard +``` + @@ -374,6 +502,36 @@ medusa.admin.giftCards.list() }) ``` + + + +```tsx +import { GiftCard } from "@medusajs/medusa" +import { useAdminGiftCards } from "medusa-react" + +const CustomGiftCards = () => { + const { gift_cards, isLoading } = useAdminGiftCards() + + return ( +
+ {isLoading && Loading...} + {gift_cards && !gift_cards.length && ( + No custom gift cards... + )} + {gift_cards && gift_cards.length > 0 && ( +
    + {gift_cards.map((giftCard: GiftCard) => ( +
  • {giftCard.code}
  • + ))} +
+ )} +
+ ) +} + +export default CustomGiftCards +``` +
@@ -421,6 +579,29 @@ medusa.admin.giftCards.create({ }) ``` + + + +```tsx +import { useAdminCreateGiftCard } from "medusa-react" + +const CreateCustomGiftCards = () => { + const createGiftCard = useAdminCreateGiftCard() + // ... + + const handleCreate = (regionId: string, value: number) => { + createGiftCard.mutate({ + region_id: regionId, + value, + }) + } + + // ... +} + +export default CreateCustomGiftCards +``` + @@ -482,6 +663,28 @@ medusa.admin.giftCards.update(giftCardId, { }) ``` + + + +```tsx +import { useAdminUpdateGiftCard } from "medusa-react" + +const UpdateCustomGiftCards = () => { + const updateGiftCard = useAdminUpdateGiftCard(customGiftCardId) + // ... + + const handleUpdate = (regionId: string) => { + updateGiftCard.mutate({ + region_id: regionId, + }) + } + + // ... +} + +export default UpdateCustomGiftCards +``` + @@ -537,6 +740,26 @@ medusa.admin.giftCards.delete(giftCardId) }) ``` + + + +```tsx +import { useAdminDeleteGiftCard } from "medusa-react" + +const CustomGiftCard = () => { + const deleteGiftCard = useAdminDeleteGiftCard(customGiftCardId) + // ... + + const handleDelete = () => { + deleteGiftCard.mutate() + } + + // ... +} + +export default CustomGiftCard +``` + diff --git a/docs/content/advanced/admin/manage-publishable-api-keys.mdx b/docs/content/advanced/admin/manage-publishable-api-keys.mdx index 2c0e210121..ceab6d2cd6 100644 --- a/docs/content/advanced/admin/manage-publishable-api-keys.mdx +++ b/docs/content/advanced/admin/manage-publishable-api-keys.mdx @@ -36,10 +36,16 @@ It is assumed that you already have a Medusa server installed and set up. If not ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -62,6 +68,38 @@ medusa.admin.publishableApiKeys.list() }) ``` + + + +```tsx +import { PublishableApiKey } from "@medusajs/medusa" +import { useAdminPublishableApiKeys } from "medusa-react" + +const PublishabelApiKeys = () => { + const { publishable_api_keys, isLoading } = useAdminPublishableApiKeys() + + return ( +
+ {isLoading && Loading...} + {publishable_api_keys && !publishable_api_keys.length && ( + No Publishable API Keys + )} + {publishable_api_keys && publishable_api_keys.length > 0 && ( +
    + {publishable_api_keys.map( + (publishableApiKey: PublishableApiKey) => ( +
  • {publishableApiKey.title}
  • + ) + )} +
+ )} +
+ ) +} + +export default PublishabelApiKeys +``` +
@@ -119,6 +157,28 @@ medusa.admin.publishableApiKeys.create({ }) ``` + + + +```tsx +import { useAdminCreatePublishableApiKey } from "medusa-react" + +const CreatePublishableApiKey = () => { + const createKey = useAdminCreatePublishableApiKey() + // ... + + const handleCreate = (title: string) => { + createKey.mutate({ + title, + }) + } + + // ... +} + +export default CreatePublishableApiKey +``` + @@ -176,6 +236,28 @@ medusa.admin.publishableApiKeys.update(publishableApiKeyId, { }) ``` + + + +```tsx +import { useAdminUpdatePublishableApiKey } from "medusa-react" + +const UpdatePublishableApiKey = () => { + const updateKey = useAdminUpdatePublishableApiKey(publishableApiKeyId) + // ... + + const handleUpdate = (title: string) => { + updateKey.mutate({ + title, + }) + } + + // ... +} + +export default UpdatePublishableApiKey +``` + @@ -233,6 +315,26 @@ medusa.admin.publishableApiKeys.revoke(publishableApiKeyId) }) ``` + + + +```tsx +import { useAdminRevokePublishableApiKey } from "medusa-react" + +const PublishableApiKey = () => { + const revokeKey = useAdminRevokePublishableApiKey(publishableApiKeyId) + // ... + + const handleRevoke = () => { + revokeKey.mutate() + } + + // ... +} + +export default PublishableApiKey +``` + @@ -279,6 +381,26 @@ medusa.admin.publishableApiKeys.delete(publishableApiKeyId) }) ``` + + + +```tsx +import { useAdminDeletePublishableApiKey } from "medusa-react" + +const PublishableApiKey = () => { + const deleteKey = useAdminDeletePublishableApiKey(publishableApiKeyId) + // ... + + const handleDelete = () => { + deleteKey.mutate() + } + + // ... +} + +export default PublishableApiKey +``` + @@ -332,6 +454,39 @@ medusa.admin.publishableApiKeys.listSalesChannels(publishableApiKeyId) }) ``` + + + +```tsx +import { SalesChannel } from "@medusajs/medusa" +import { useAdminPublishableApiKeySalesChannels } from "medusa-react" + +const SalesChannels = () => { + const { sales_channels, isLoading } = + useAdminPublishableApiKeySalesChannels( + publishableApiKeyId + ) + + return ( +
+ {isLoading && Loading...} + {sales_channels && !sales_channels.length && ( + No Sales Channels + )} + {sales_channels && sales_channels.length > 0 && ( +
    + {sales_channels.map((salesChannel: SalesChannel) => ( +
  • {salesChannel.name}
  • + ))} +
+ )} +
+ ) +} + +export default SalesChannels +``` +
@@ -388,6 +543,34 @@ medusa.admin.publishableApiKeys.addSalesChannelsBatch( }) ``` + + + +```tsx +import { useAdminAddPublishableKeySalesChannelsBatch } from "medusa-react" + +const PublishableApiKey = () => { + const addSalesChannels = useAdminAddPublishableKeySalesChannelsBatch( + publishableApiKeyId + ) + // ... + + const handleAdd = (salesChannelId: string) => { + addSalesChannels.mutate({ + sales_channel_ids: [ + { + id: salesChannelId, + }, + ], + }) + } + + // ... +} + +export default PublishableApiKey +``` + @@ -467,6 +650,37 @@ medusa.admin.publishableApiKeys.deleteSalesChannelsBatch( }) ``` + + + +```tsx +import { + useAdminRemovePublishableKeySalesChannelsBatch, +} from "medusa-react" + +const PublishableApiKey = () => { + const deleteSalesChannels = + useAdminRemovePublishableKeySalesChannelsBatch( + publishableApiKeyId + ) + // ... + + const handleDelete = (salesChannelId: string) => { + deleteSalesChannels.mutate({ + sales_channel_ids: [ + { + id: salesChannelId, + }, + ], + }) + } + + // ... +} + +export default PublishableApiKey +``` + diff --git a/docs/content/advanced/admin/manage-regions.mdx b/docs/content/advanced/admin/manage-regions.mdx index 52def1da8e..3884aed775 100644 --- a/docs/content/advanced/admin/manage-regions.mdx +++ b/docs/content/advanced/admin/manage-regions.mdx @@ -35,10 +35,16 @@ It is assumed that you already have a Medusa server installed and set up. If not ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -54,7 +60,7 @@ You can retrieve regions available on your server using the [List Regions](/api/ -```tsx +```ts medusa.admin.regions.list() .then(({ regions, limit, offset, count }) => { console.log(regions.length) @@ -63,9 +69,37 @@ medusa.admin.regions.list() ``` - + ```tsx +import { Region } from "@medusajs/medusa" +import { useAdminRegions } from "medusa-react" + +const Regions = () => { + const { regions, isLoading } = useAdminRegions() + + return ( +
+ {isLoading && Loading...} + {regions && !regions.length && No Regions} + {regions && regions.length > 0 && ( +
    + {regions.map((region: Region) => ( +
  • {region.name}
  • + ))} +
+ )} +
+ ) +} + +export default Regions +``` + +
+ + +```ts fetch(`/admin/regions`, { credentials: "include", }) @@ -100,7 +134,7 @@ You can create a region by sending a request to the [Create a Region](/api/admin -```tsx +```ts medusa.admin.regions.create({ name: "Europe", currency_code: "eur", @@ -121,9 +155,42 @@ medusa.admin.regions.create({ ``` - + ```tsx +import { useAdminCreateRegion } from "medusa-react" + +const CreateRegion = () => { + const createRegion = useAdminCreateRegion() + // ... + + const handleCreate = () => { + createRegion.mutate({ + name: "Europe", + currency_code: "eur", + tax_rate: 0, + payment_providers: [ + "manual", + ], + fulfillment_providers: [ + "manual", + ], + countries: [ + "DK", + ], + }) + } + + // ... +} + +export default CreateRegion +``` + + + + +```ts fetch(`/admin/regions`, { credentials: "include", method: "POST", @@ -198,7 +265,7 @@ Alternatively, you can update the details of a region using the [Update a Region -```tsx +```ts medusa.admin.regions.update(regionId, { countries: [ "DK", @@ -211,9 +278,34 @@ medusa.admin.regions.update(regionId, { ``` - + ```tsx +import { useAdminUpdateRegion } from "medusa-react" + +const UpdateRegion = () => { + const updateRegion = useAdminUpdateRegion(regionId) + // ... + + const handleUpdate = () => { + updateRegion.mutate({ + countries: [ + "DK", + "DE", + ], + }) + } + + // ... +} + +export default UpdateRegion +``` + + + + +```ts fetch(`/admin/regions/${regionId}`, { credentials: "include", method: "POST", @@ -269,7 +361,7 @@ You can add a shipping option to a region by sending a request to the [Create Sh -```tsx +```ts medusa.admin.shippingOptions.create({ name: "PostFake", region_id: regionId, @@ -285,9 +377,37 @@ medusa.admin.shippingOptions.create({ ``` - + ```tsx +import { useAdminCreateShippingOption } from "medusa-react" + +const Region = () => { + const createShippingOption = useAdminCreateShippingOption() + // ... + + const handleCreate = () => { + createShippingOption.mutate({ + name: "PostFake", + region_id: regionId, + provider_id: "manual", + data: { + }, + price_type: "flat_rate", + amount: 1000, + }) + } + + // ... +} + +export default Region +``` + + + + +```ts fetch(`/admin/shipping-options`, { credentials: "include", method: "POST", @@ -357,7 +477,7 @@ You can delete a region by sending a request to the [Delete a Region](/api/admin -```tsx +```ts medusa.admin.regions.delete(regionId) .then(({ id, object, deleted }) => { console.log(id) @@ -365,9 +485,29 @@ medusa.admin.regions.delete(regionId) ``` - + ```tsx +import { useAdminDeleteRegion } from "medusa-react" + +const Region = () => { + const deleteRegion = useAdminDeleteRegion(regionId) + // ... + + const handleDelete = () => { + deleteRegion.mutate() + } + + // ... +} + +export default Region +``` + + + + +```ts fetch(`/admin/regions/${regionId}`, { credentials: "include", method: "DELETE", diff --git a/docs/content/advanced/admin/order-edit.mdx b/docs/content/advanced/admin/order-edit.mdx index 8267e834f4..deb00593c7 100644 --- a/docs/content/advanced/admin/order-edit.mdx +++ b/docs/content/advanced/admin/order-edit.mdx @@ -49,10 +49,16 @@ It is assumed that you already have a Medusa server installed and set up. If not ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -83,6 +89,27 @@ medusa.admin.orderEdits.create({ }) ``` + + + +```tsx +import { useAdminCreateOrderEdit } from "medusa-react" + +const OrderEdit = () => { + const createOrderEdit = useAdminCreateOrderEdit() + + const handleCreateOrderEdit = (orderId: string) => { + createOrderEdit.mutate({ + order_id: orderId, + }) + } + + // ... +} + +export default OrderEdit +``` + @@ -157,6 +184,28 @@ medusa.admin.orderEdits.addLineItem(orderEditId, { }) ``` + + + +```tsx +import { useAdminOrderEditAddLineItem } from "medusa-react" + +const OrderEdit = () => { + const addLineItem = useAdminOrderEditAddLineItem(orderEditId) + + const handleAddLineItem = (quantity: number, variantId: string) => { + addLineItem.mutate({ + quantity, + variant_id: variantId, + }) + } + + // ... +} + +export default OrderEdit +``` + @@ -218,6 +267,30 @@ medusa.admin.orderEdits.updateLineItem(orderEditId, itemId, { }) ``` + + + +```tsx +import { useAdminOrderEditUpdateLineItem } from "medusa-react" + +const OrderEdit = () => { + const updateLineItem = useAdminOrderEditUpdateLineItem( + orderEditId, + itemId + ) + + const handleUpdateLineItem = (quantity: number) => { + updateLineItem.mutate({ + quantity, + }) + } + + // ... +} + +export default OrderEdit +``` + @@ -273,6 +346,28 @@ medusa.admin.orderEdits.removeLineItem(orderEditId, itemId) }) ``` + + + +```tsx +import { useAdminOrderEditDeleteLineItem } from "medusa-react" + +const OrderEdit = () => { + const removeLineItem = useAdminOrderEditDeleteLineItem( + orderEditId, + itemId + ) + + const handleRemoveLineItem = () => { + removeLineItem.mutate() + } + + // ... +} + +export default OrderEdit +``` + @@ -320,6 +415,28 @@ medusa.admin.orderEdits.deleteItemChange(orderEditId, changeId) }) ``` + + + +```tsx +import { useAdminDeleteOrderEditItemChange } from "medusa-react" + +const OrderEdit = () => { + const deleteItemChange = useAdminDeleteOrderEditItemChange( + orderEditId, + itemChangeId + ) + + const handleDeleteItemChange = () => { + deleteItemChange.mutate() + } + + // ... +} + +export default OrderEdit +``` + @@ -374,6 +491,28 @@ medusa.admin.orderEdits.requestConfirmation(orderEditId) }) ``` + + + +```tsx +import { useAdminRequestOrderEditConfirmation } from "medusa-react" + +const OrderEdit = () => { + const requestOrderConfirmation = + useAdminRequestOrderEditConfirmation( + orderEditId + ) + + const handleRequestConfirmation = () => { + requestOrderConfirmation.mutate() + } + + // ... +} + +export default OrderEdit +``` + @@ -441,6 +580,25 @@ medusa.admin.orderEdits.confirm(orderEditId) }) ``` + + + +```tsx +import { useAdminConfirmOrderEdit } from "medusa-react" + +const OrderEdit = () => { + const confirmOrderEdit = useAdminConfirmOrderEdit(orderEditId) + + const handleConfirmOrderEdit = () => { + confirmOrderEdit.mutate() + } + + // ... +} + +export default OrderEdit +``` + @@ -503,6 +661,25 @@ medusa.admin.payments.capturePayment(paymentId) }) ``` + + + +```tsx +import { useAdminPaymentsCapturePayment } from "medusa-react" + +const OrderEditPayment = () => { + const capturePayment = useAdminPaymentsCapturePayment(paymentId) + + const handleCapturePayment = () => { + capturePayment.mutate() + } + + // ... +} + +export default OrderEditPayment +``` + @@ -542,14 +719,41 @@ To refund the difference to the customer, send a request to the [Refund Payment] ```ts +import { RefundReason } from "@medusajs/medusa" +// ... + medusa.admin.payments.refundPayment(paymentId, { amount, + reason: RefundReason.DISCOUNT, // for example }) .then(({ refund }) => { console.log(refund.id) }) ``` + + + +```tsx +import { useAdminPaymentsRefundPayment } from "medusa-react" +import { RefundReason } from "@medusajs/medusa" + +const OrderEditPayment = () => { + const refundPayment = useAdminPaymentsRefundPayment(paymentId) + + const handleRefundPayment = (amount: number, reason: RefundReason) => { + refundPayment.mutate({ + amount, + reason, + }) + } + + // ... +} + +export default OrderEditPayment +``` + @@ -562,6 +766,7 @@ fetch(`/admin/payments/${paymentId}/refund`, { }, body: JSON.stringify({ amount, + reason: "discount", }), }) .then((response) => response.json()) @@ -578,7 +783,8 @@ curl -L -X POST '/admin/payments//refund' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ --data-raw '{ - "amount": 1000 + "amount": 1000, + "reason": "discount" }' ``` @@ -589,6 +795,14 @@ This request requires the ID of the payment as a path parameter. The payment can In the request’s body parameters, the `amount` field parameter is required. It is the amount to be refunded. +The `reason` request body parameter is also required. Its value is a string that can be one of the following: + +- `discount` +- `return` +- `swap` +- `claim` +- `other` + :::note Check out what other parameters can be sent in the [API reference](/api/admin/#tag/Payment/operation/PostPaymentsPaymentRefunds). diff --git a/docs/content/advanced/admin/use-customergroups-api.mdx b/docs/content/advanced/admin/use-customergroups-api.mdx index 346a1e0a08..e076a49593 100644 --- a/docs/content/advanced/admin/use-customergroups-api.mdx +++ b/docs/content/advanced/admin/use-customergroups-api.mdx @@ -23,10 +23,16 @@ It is assumed that you already have a Medusa server installed and set up. If not ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../js-client/overview.md) installed and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -42,7 +48,7 @@ You can create a customer group by sending a request to the Create Customer Grou -```jsx +```ts medusa.admin.customerGroups.create({ name: "VIP", }) @@ -51,10 +57,38 @@ medusa.admin.customerGroups.create({ }) ``` + + + +```tsx +import { useAdminCreateCustomerGroup } from "medusa-react" + +const CreateCustomerGroup = () => { + const createCustomerGroup = useAdminCreateCustomerGroup() + // ... + + const handleCreate = () => { + createCustomerGroup.mutate({ + name, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default CreateCustomerGroup +``` +
-```jsx +```ts fetch(`/admin/customer-groups`, { method: "POST", credentials: "include", @@ -97,17 +131,47 @@ You can get a list of all customer groups by sending a request to the List Custo -```jsx +```ts medusa.admin.customerGroups.list() .then(({ customer_groups, limit, offset, count }) => { console.log(customer_groups.length) }) ``` + + + +```tsx +import { CustomerGroup } from "@medusajs/medusa" +import { useAdminCustomerGroups } from "medusa-react" + +const CustomerGroups = () => { + const { customer_groups, isLoading } = useAdminCustomerGroups() + + return ( +
+ {isLoading && Loading...} + {customer_groups && !customer_groups.length && ( + No Customer Groups + )} + {customer_groups && customer_groups.length > 0 && ( +
    + {customer_groups.map((customerGroup: CustomerGroup) => ( +
  • {customerGroup.name}
  • + ))} +
+ )} +
+ ) +} + +export default CustomerGroups +``` +
-```jsx +```ts fetch(`/admin/customer-groups`, { credentials: "include", }) @@ -141,17 +205,39 @@ You can retrieve a single customer group by sending a request to the Get a Custo -```jsx +```ts medusa.admin.customerGroups.retrieve(customerGroupId) .then(({ customer_group }) => { console.log(customer_group.id) }) ``` + + + +```tsx +import { useAdminCustomerGroup } from "medusa-react" + +const CustomerGroup = () => { + const { customer_group, isLoading } = useAdminCustomerGroup( + customerGroupId + ) + + return ( +
+ {isLoading && Loading...} + {customer_group && {customer_group.name}} +
+ ) +} + +export default CustomerGroup +``` +
-```jsx +```ts fetch(`/admin/customer-groups/${customerGroupId}`, { credentials: "include", }) @@ -183,7 +269,7 @@ You can update a customer group’s data by sending a request to the Update Cust -```jsx +```ts medusa.admin.customerGroups.update(customerGroupId, { metadata: { is_seller: true, @@ -194,10 +280,38 @@ medusa.admin.customerGroups.update(customerGroupId, { }) ``` + + + +```tsx +import { useAdminUpdateCustomerGroup } from "medusa-react" + +const UpdateCustomerGroup = () => { + const updateCustomerGroup = useAdminUpdateCustomerGroup(customerGroupId) + // .. + + const handleUpdate = () => { + updateCustomerGroup.mutate({ + name, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default UpdateCustomerGroup +``` +
-```jsx +```ts fetch(`/admin/customer-groups/${customerGroupId}`, { method: "POST", credentials: "include", @@ -244,17 +358,37 @@ You can delete a customer group by sending a request to the Delete a Customer Gr -```jsx +```ts medusa.admin.customerGroups.delete(customerGroupId) .then(({ id, object, deleted }) => { console.log(id) }) ``` + + + +```tsx +import { useAdminDeleteCustomerGroup } from "medusa-react" + +const CustomerGroup = () => { + const deleteCustomerGroup = useAdminDeleteCustomerGroup(customerGroupId) + // ... + + const handleDeleteCustomerGroup = () => { + deleteCustomerGroup.mutate() + } + + // ... +} + +export default CustomerGroup +``` + -```jsx +```ts fetch(`/admin/customer-groups/${customerGroupId}`, { method: "DELETE", credentials: "include", @@ -289,7 +423,7 @@ You can add a customer to a group by sending a request to the Customer Group’s -```jsx +```ts medusa.admin.customerGroups.addCustomers(customerGroupId, { customer_ids: [ { @@ -302,10 +436,36 @@ medusa.admin.customerGroups.addCustomers(customerGroupId, { }) ``` + + + +```tsx +import { useAdminAddCustomersToCustomerGroup } from "medusa-react" + +const CustomerGroup = () => { + const addCustomers = useAdminAddCustomersToCustomerGroup(customerGroupId) + // ... + + const handleAddCustomers= (customerId: string) => { + addCustomers.mutate({ + customer_ids: [ + { + id: customerId, + }, + ], + }) + } + + // ... +} + +export default CustomerGroup +``` + -```jsx +```ts fetch( `/admin/customer-groups/${customerGroupId}/customers/batch`, { @@ -357,17 +517,47 @@ You can retrieve a list of all customers in a customer group using the List Cust -```jsx +```ts medusa.admin.customerGroups.listCustomers(customerGroupId) .then(({ customers, count, offset, limit }) => { console.log(customers.length) }) ``` + + + +```tsx +import { Customer } from "@medusajs/medusa" +import { useAdminCustomerGroupCustomers } from "medusa-react" + +const CustomerGroup = () => { + const { customers, isLoading } = useAdminCustomerGroupCustomers( + customerGroupId + ) + + return ( +
+ {isLoading && Loading...} + {customers && !customers.length && No customers} + {customers && customers.length > 0 && ( +
    + {customers.map((customer: Customer) => ( +
  • {customer.first_name}
  • + ))} +
+ )} +
+ ) +} + +export default CustomerGroup +``` +
-```jsx +```ts fetch(`/admin/customer-groups/${customerGroupId}/customers`, { credentials: "include", }) @@ -403,7 +593,7 @@ You can remove customers from a customer group by sending a request to the Remov -```jsx +```ts medusa.admin.customerGroups.removeCustomers(customer_group_id, { customer_ids: [ { @@ -416,10 +606,39 @@ medusa.admin.customerGroups.removeCustomers(customer_group_id, { }) ``` + + + +```tsx +import { Customer } from "@medusajs/medusa" +import { useAdminRemoveCustomersFromCustomerGroup } from "medusa-react" + +const CustomerGroup = () => { + const removeCustomers = useAdminRemoveCustomersFromCustomerGroup( + customerGroupId + ) + // ... + + const handleRemoveCustomer = (customer_id: string) => { + removeCustomers.mutate({ + customer_ids: [ + { + id: customer_id, + }, + ], + }) + } + + // ... +} + +export default CustomerGroup +``` + -```jsx +```ts fetch( `/admin/customer-groups/${customerGroupId}/customers/batch`, { diff --git a/docs/content/advanced/backend/price-lists/use-api.mdx b/docs/content/advanced/backend/price-lists/use-api.mdx index 03b190f827..b471bb45eb 100644 --- a/docs/content/advanced/backend/price-lists/use-api.mdx +++ b/docs/content/advanced/backend/price-lists/use-api.mdx @@ -23,6 +23,12 @@ This guide includes code snippets to send requests to your Medusa server using M If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client](../../../js-client/overview.md) installed and [have created an instance of the client](../../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in the tutorial. @@ -69,13 +75,13 @@ For example, sending the following request creates a price list with two prices: ```jsx -import { PriceListType } from "@medusajs/medusa" +import { PriceListStatus, PriceListType } from "@medusajs/medusa" medusa.admin.priceLists.create({ name: "New Price List", description: "A new price list", type: PriceListType.SALE, - status: "active", + status: PriceListStatus.ACTIVE, prices: [ { amount: 1000, @@ -96,6 +102,46 @@ medusa.admin.priceLists.create({ }) ``` + + + +```tsx +import { PriceListStatus, PriceListType } from "@medusajs/medusa" +import { useAdminCreatePriceList } from "medusa-react" + +const CreatePriceList = () => { + const createPriceList = useAdminCreatePriceList() + // ... + + const handleCreate = () => { + createPriceList.mutate({ + name: "New Price List", + description: "A new price list", + type: PriceListType.SALE, + status: PriceListStatus.ACTIVE, + prices: [ + { + amount: 1000, + variant_id, + currency_code: "eur", + max_quantity: 3, + }, + { + amount: 1500, + variant_id, + currency_code: "eur", + min_quantity: 4, + }, + ], + }) + } + + // ... +} + +export default CreatePriceList +``` + @@ -185,6 +231,27 @@ medusa.admin.priceLists.retrieve(priceListId) }) ``` + + + +```tsx +import { CustomerGroup } from "@medusajs/medusa" +import { useAdminPriceList } from "medusa-react" + +const PriceList = () => { + const { price_list, isLoading } = useAdminPriceList(priceListId) + + return ( +
+ {isLoading && Loading...} + {price_list && {price_list.name}} +
+ ) +} + +export default PriceList +``` +
@@ -229,6 +296,29 @@ medusa.admin.priceLists.update(priceListId, { }) ``` + + + +```tsx +import { PriceListStatus, PriceListType } from "@medusajs/medusa" +import { useAdminUpdatePriceList } from "medusa-react" + +const CreatePriceList = () => { + const updatePriceList = useAdminUpdatePriceList(priceListId) + // ... + + const handleUpdate = () => { + updatePriceList.mutate({ + ends_at: "2022-10-11", + }) + } + + // ... +} + +export default CreatePriceList +``` + @@ -298,6 +388,34 @@ medusa.admin.priceLists.addPrices(priceListId, { }) ``` + + + +```tsx +import { useAdminCreatePriceListPrices } from "medusa-react" + +const PriceList = () => { + const addPrice = useAdminCreatePriceListPrices(priceListId) + // ... + + const handleAddPrice = () => { + addPrice.mutate({ + prices: [ + { + amount: 1200, + variant_id, + currency_code: "eur", + }, + ], + }) + } + + // ... +} + +export default PriceList +``` + @@ -363,6 +481,29 @@ medusa.admin.priceLists.deleteProductPrices(priceListId, productId) }) ``` + + + +```tsx +import { useAdminDeletePriceListProductPrices } from "medusa-react" + +const PriceList = () => { + const deletePrices = useAdminDeletePriceListProductPrices( + priceListId, + productId + ) + // ... + + const handleDeletePrices = () => { + deletePrices.mutate() + } + + // ... +} + +export default PriceList +``` + @@ -409,6 +550,29 @@ medusa.admin.priceLists.deleteVariantPrices(priceListId, variantId) }) ``` + + + +```tsx +import { useAdminDeletePriceListVariantPrices } from "medusa-react" + +const PriceList = () => { + const deleteVariantPrices = useAdminDeletePriceListVariantPrices( + priceListId, + variantId + ) + // ... + + const handleDeletePrices = () => { + deleteVariantPrices.mutate() + } + + // ... +} + +export default PriceList +``` + @@ -457,6 +621,26 @@ medusa.admin.priceLists.delete(priceListId) }) ``` + + + +```tsx +import { useAdminDeletePriceList } from "medusa-react" + +const PriceList = () => { + const deletePriceList = useAdminDeletePriceList(priceListId) + // ... + + const handleDeletePriceList = () => { + deletePriceList.mutate() + } + + // ... +} + +export default PriceList +``` + diff --git a/docs/content/advanced/backend/sales-channels/manage-admin.mdx b/docs/content/advanced/backend/sales-channels/manage-admin.mdx index 2cb813ee95..8018bfeaa5 100644 --- a/docs/content/advanced/backend/sales-channels/manage-admin.mdx +++ b/docs/content/advanced/backend/sales-channels/manage-admin.mdx @@ -25,21 +25,18 @@ This guide explains how to perform all these operations using the Admin APIs. It's assumed that you already have a Medusa server installed and set up. If not, you can follow our [quickstart guide](../../../quickstart/quick-start.mdx) to get started. -### Enabled Feature Flags - -The Sales Channels feature is currently in beta mode and guarded by a feature flag. To use sales channels either: - -1. Enable the `MEDUSA_FF_SALES_CHANNELS` environment variable; -2. Or enable the `sales_channels` key in the Medusa server's settings. - -You can learn more about enabling it in the [feature flags](../feature-flags/toggle.md) documentation. - ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, JavaScript’s Fetch API, or cURL. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../../js-client/overview.md) and [have created an instance of the client](../../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../../medusa-react/overview.md#usage). + ### Authenticated Admin User You must be an authenticated admin user before following along with the steps in this guide. @@ -55,7 +52,7 @@ You can create a sales channel by sending a request to the Create a Sales Channe -```jsx +```ts medusa.admin.salesChannels.create({ name: "App", description: "Mobile app", @@ -65,10 +62,33 @@ medusa.admin.salesChannels.create({ }) ``` + + + +```tsx +import { useAdminCreateSalesChannel } from "medusa-react" + +const CreateSalesChannel = () => { + const createSalesChannel = useAdminCreateSalesChannel() + // ... + + const handleCreate = (name: string, description: string) => { + createSalesChannel.mutate({ + name, + description, + }) + } + + // ... +} + +export default CreateSalesChannel +``` + -```jsx +```ts fetch(`/admin/sales-channels`, { method: "POST", credentials: "include", @@ -115,17 +135,47 @@ You can list all sales channels by sending a request to the List Sales Channels -```jsx +```ts medusa.admin.salesChannels.list() .then(({ sales_channels, limit, offset, count }) => { console.log(sales_channels.length) }) ``` + + + +```tsx +import { SalesChannel } from "@medusajs/medusa" +import { useAdminSalesChannels } from "medusa-react" + +const SalesChannels = () => { + const { sales_channels, isLoading } = useAdminSalesChannels() + + return ( +
+ {isLoading && Loading...} + {sales_channels && !sales_channels.length && ( + No Sales Channels + )} + {sales_channels && sales_channels.length > 0 && ( +
    + {sales_channels.map((salesChannel: SalesChannel) => ( +
  • {salesChannel.name}
  • + ))} +
+ )} +
+ ) +} + +export default SalesChannels +``` +
-```jsx +```ts fetch(`/admin/sales-channels`, { credentials: "include", }) @@ -157,17 +207,37 @@ You can retrieve a sales channel’s details by its ID using the Get Sales Chann -```jsx +```ts medusa.admin.salesChannels.retrieve(salesChannelId) .then(({ sales_channel }) => { console.log(sales_channel.id) }) ``` + + + +```tsx +import { useAdminSalesChannel } from "medusa-react" + +const SalesChannel = () => { + const { sales_channel, isLoading } = useAdminSalesChannel(salesChannelId) + + return ( +
+ {isLoading && Loading...} + {sales_channel && {sales_channel.name}} +
+ ) +} + +export default SalesChannel +``` +
-```jsx +```ts fetch(`/admin/sales-channels/${salesChannelId}`, { credentials: "include", }) @@ -199,7 +269,7 @@ You can update a Sales Channel’s details and attributes by sending a request t -```jsx +```ts medusa.admin.salesChannels.update(salesChannelId, { is_disabled: false, }) @@ -208,10 +278,32 @@ medusa.admin.salesChannels.update(salesChannelId, { }) ``` + + + +```tsx +import { useAdminUpdateSalesChannel } from "medusa-react" + +const UpdateSalesChannel = () => { + const updateSalesChannel = useAdminUpdateSalesChannel(salesChannelId) + // ... + + const handleUpdate = () => { + updateSalesChannel.mutate({ + is_disabled: false, + }) + } + + // ... +} + +export default UpdateSalesChannel +``` + -```jsx +```ts fetch(`/admin/sales-channels/${salesChannelId}`, { method: "POST", credentials: "include", @@ -258,17 +350,37 @@ You can delete a sales channel by sending a request to the Delete Sales Channel -```jsx +```ts medusa.admin.salesChannels.delete(salesChannelId) .then(({ id, object, deleted }) => { console.log(id) }) ``` + + + +```tsx +import { useAdminDeleteSalesChannel } from "medusa-react" + +const SalesChannel = () => { + const deleteSalesChannel = useAdminDeleteSalesChannel(salesChannelId) + // ... + + const handleDelete = () => { + deleteSalesChannel.mutate() + } + + // ... +} + +export default SalesChannel +``` + -```jsx +```ts fetch(`/admin/sales-channels/${salesChannelId}`, { method: "DELETE", credentials: "include", @@ -303,7 +415,7 @@ To add a product to a sales channel, send a request to the Sales Channel’s Add -```jsx +```ts medusa.admin.salesChannels.addProducts(salesChannelId, { product_ids: [ { @@ -316,10 +428,36 @@ medusa.admin.salesChannels.addProducts(salesChannelId, { }) ``` + + + +```tsx +import { useAdminAddProductsToSalesChannel } from "medusa-react" + +const SalesChannel = () => { + const addProducts = useAdminAddProductsToSalesChannel(salesChannelId) + // ... + + const handleAddProducts = (productId: string) => { + addProducts.mutate({ + product_ids: [ + { + id: productId, + }, + ], + }) + } + + // ... +} + +export default SalesChannel +``` + -```jsx +```ts fetch( `/admin/sales-channels/${salesChannelId}/products/batch`, { @@ -373,7 +511,7 @@ You can list the products available in a sales channel by sending a request to t -```jsx +```ts medusa.admin.products.list({ sales_channel_id: [ salesChannelId, @@ -384,10 +522,41 @@ medusa.admin.products.list({ }) ``` + + + +```tsx +import { Product } from "@medusajs/medusa" +import { PricedProduct } from "@medusajs/medusa/dist/types/pricing" +import { useAdminProducts } from "medusa-react" + +const SalesChannelProducts = () => { + const { products, isLoading } = useAdminProducts({ + sales_channel_id: [salesChannelId], + }) + + return ( +
+ {isLoading && Loading...} + {products && products.length > 0 && ( +
    + {products.map((product: (Product | PricedProduct)) => ( +
  • {product.title}
  • + ))} +
+ )} + {products && !products.length && No Products} +
+ ) +} + +export default SalesChannelProducts +``` +
-```jsx +```ts fetch( `/admin/products?sales_channel_id[0]=${salesChannelId}`, { @@ -426,7 +595,7 @@ You can delete a product from a sales channel by sending a request to the Sales -```jsx +```ts medusa.admin.salesChannels.removeProducts(salesChannelId, { product_ids: [ { @@ -439,10 +608,38 @@ medusa.admin.salesChannels.removeProducts(salesChannelId, { }) ``` + + + +```tsx +import { useAdminDeleteProductsFromSalesChannel } from "medusa-react" + +const SalesChannel = () => { + const deleteProducts = useAdminDeleteProductsFromSalesChannel( + salesChannelId + ) + // ... + + const handleDeleteProducts = (productId: string) => { + deleteProducts.mutate({ + product_ids: [ + { + id: productId, + }, + ], + }) + } + + // ... +} + +export default SalesChannel +``` + -```jsx +```ts fetch( `/admin/sales-channels/${salesChannelId}/products/batch`, { @@ -498,7 +695,7 @@ You can filter orders by a specific sales channel by sending a request to the Li -```jsx +```ts medusa.admin.orders.list({ sales_channel_id: [ salesChannelId, @@ -511,10 +708,42 @@ medusa.admin.orders.list({ }) ``` + + + +```tsx +import { Order } from "@medusajs/medusa" +import { useAdminOrders } from "medusa-react" + +const SalesChannelOrders = () => { + const { orders, isLoading } = useAdminOrders({ + sales_channel_id: [salesChannelId], + offset: 0, + limit: 50, + }) + + return ( +
+ {isLoading && Loading...} + {orders && orders.length > 0 && ( +
    + {orders.map((order: Order) => ( +
  • {order.display_id}
  • + ))} +
+ )} + {orders && !orders.length && No Orders} +
+ ) +} + +export default SalesChannelOrders +``` +
-```jsx +```ts fetch(`/admin/orders?sales_channel_id[0]=${salesChannelId}`, { credentials: "include", }) diff --git a/docs/content/advanced/storefront/customer-profiles.mdx b/docs/content/advanced/storefront/customer-profiles.mdx index 7eb1b5bbd2..1e7f4d8c55 100644 --- a/docs/content/advanced/storefront/customer-profiles.mdx +++ b/docs/content/advanced/storefront/customer-profiles.mdx @@ -37,10 +37,16 @@ It's also assumed you already have a storefront set up. It can be a custom store ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + --- ## Register a Customer @@ -64,6 +70,38 @@ medusa.customers.create({ }) ``` + + + +```tsx +import { useCreateCustomer } from "medusa-react" + +const RegisterCustomer = () => { + const createCustomer = useCreateCustomer() + // ... + + const handleCreate = () => { + // ... + createCustomer.mutate({ + first_name, + last_name, + email, + password, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default RegisterCustomer +``` +
@@ -321,6 +359,36 @@ medusa.customers.update({ }) ``` + + + +```tsx +import { useUpdateMe } from "medusa-react" + +const UpdateCustomer = () => { + const updateCustomer = useUpdateMe() + // ... + + const handleUpdate = () => { + // ... + updateCustomer.mutate({ + id: customer_id, + first_name, + }) + } + + // ... + + return ( +
+ {/* Render form */} +
+ ) +} + +export default UpdateCustomer +``` +
@@ -530,6 +598,35 @@ medusa.customers.listOrders() }) ``` + + + +```tsx +import { useCustomerOrders } from "medusa-react" +import { Order } from "@medusajs/medusa" + +const Orders = () => { + // refetch a function that can be used to + // re-retrieve orders after the customer logs in + const { orders, isLoading, refetch } = useCustomerOrders() + + return ( +
+ {isLoading && Loading orders...} + {orders?.length && ( +
    + {orders.map((order: Order) => ( +
  • {order.display_id}
  • + ))} +
+ )} +
+ ) +} + +export default Orders +``` +
diff --git a/docs/content/advanced/storefront/handle-order-edits.mdx b/docs/content/advanced/storefront/handle-order-edits.mdx index 40659c4071..47ecdc2019 100644 --- a/docs/content/advanced/storefront/handle-order-edits.mdx +++ b/docs/content/advanced/storefront/handle-order-edits.mdx @@ -51,6 +51,12 @@ This guide includes code snippets to send requests to your Medusa server using M If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Previous Steps You must have an existing order edit in the “request” state. @@ -72,6 +78,21 @@ medusa.orderEdits.retrieve(orderEditId) }) ``` + + + +```ts +import { useOrderEdit } from "medusa-react" + +const OrderEdit = () => { + const { order_edit, isLoading } = useOrderEdit(orderEditId) + + // ... +} + +export default OrderEdit +``` + @@ -123,7 +144,7 @@ All data about changes to the original order’s items can be found in `order_ed Here’s an example of how you can use this data to show the customer the requested edits to the order: -```jsx +```tsx
    {orderEdit.changes.map((itemChange) => (
  • @@ -184,6 +205,28 @@ medusa.paymentCollections.managePaymentSession(paymentCollectionId, { }) ``` + + + +```ts +import { useManagePaymentSession } from "medusa-react" + +const OrderEditPayment = () => { + const managePaymentSession = useManagePaymentSession(paymentCollectionId) + // ... + + const handleAdditionalPayment = (provider_id: string) => { + managePaymentSession.mutate({ + provider_id, + }) + } + + // ... +} + +export default OrderEditPayment +``` + @@ -224,6 +267,28 @@ medusa.paymentCollection }) ``` + + + +```ts +import { useAuthorizePaymentSession } from "medusa-react" + +const OrderEditPayment = () => { + const authorizePaymentSession = useAuthorizePaymentSession( + paymentCollectionId + ) + // ... + + const handleAuthorizePayment = (paymentSessionId: string) => { + authorizePaymentSession.mutate(paymentSessionId) + } + + // ... +} + +export default OrderEditPayment +``` + @@ -263,6 +328,26 @@ medusa.orderEdits.complete(orderEditId) }) ``` + + + +```ts +import { useCompleteOrderEdit } from "medusa-react" + +const OrderEdit = () => { + const completeOrderEdit = useCompleteOrderEdit(orderEditId) + // ... + + const handleCompleteOrderEdit = () => { + completeOrderEdit.mutate() + } + + // ... +} + +export default OrderEdit +``` + @@ -310,6 +395,28 @@ medusa.orderEdits.decline(orderEditId, { }) ``` + + + +```ts +import { useDeclineOrderEdit } from "medusa-react" + +const OrderEdit = () => { + const declineOrderEdit = useDeclineOrderEdit(orderEditId) + // ... + + const handleDeclineOrderEdit = () => { + declineOrderEdit.mutate({ + declined_reason: "I am not satisfied", + }) + } + + // ... +} + +export default OrderEdit +``` + diff --git a/docs/content/advanced/storefront/how-to-implement-checkout-flow.mdx b/docs/content/advanced/storefront/how-to-implement-checkout-flow.mdx index 307d7c276b..b09637cd0d 100644 --- a/docs/content/advanced/storefront/how-to-implement-checkout-flow.mdx +++ b/docs/content/advanced/storefront/how-to-implement-checkout-flow.mdx @@ -33,6 +33,14 @@ This guide includes code snippets to send requests to your Medusa server using M If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + +It's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider). + ### Previous Steps This document assumes you’ve already taken care of the add-to-cart flow. So, you should have a [cart created](/api/store/#tag/Cart/operation/PostCart) for the customer with at least [one product in it](/api/store/#tag/Cart/operation/PostCartsCartLineItems). @@ -52,7 +60,7 @@ After the customer enters their shipping address information, you must send a `P -```jsx +```ts medusa.carts.update(cartId, { shipping_address: { company, @@ -72,10 +80,44 @@ medusa.carts.update(cartId, { }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const addShippingAddress = (address: Record) => { + updateCart.mutate({ + shipping_address: { + company: address.company, + first_name: address.first_name, + last_name: address.last_name, + address_1: address.address_1, + address_2: address.address_2, + city: address.city, + country_code: address.country_code, + province: address.province, + postal_code: address.postal_code, + phone: address.phone, + }, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", @@ -121,17 +163,51 @@ You can retrieve the list of shipping options by sending a `GET` request to the -```jsx +```ts medusa.shippingOptions.listCartOptions(cartId) .then(({ shipping_options }) => { console.log(shipping_options.length) }) ``` + + + +```tsx +import { ShippingOption } from "@medusajs/medusa" +import { useCartShippingOptions } from "medusa-react" + +type Props = { + cartId: string +} + +const ShippingOptions = ({ cartId }: Props) => { + const { shipping_options, isLoading } = useCartShippingOptions(cartId) + + return ( +
    + {isLoading && Loading...} + {shipping_options && !shipping_options.length && ( + No shipping options + )} + {shipping_options && ( +
      + {shipping_options.map((shipping_option: ShippingOption) => ( +
    • {shipping_option.name}
    • + ))} +
    + )} +
    + ) +} + +export default ShippingOptions +``` +
    -```jsx +```ts fetch(`/store/shipping-options/${cartId}`, { credentials: "include", }) @@ -153,7 +229,7 @@ Once the customer chooses one of the available shipping options, send a `POST` r -```jsx +```ts medusa.carts.addShippingMethod(cartId, { option_id: shippingOptionId, // the ID of the selected option }) @@ -162,10 +238,33 @@ medusa.carts.addShippingMethod(cartId, { }) ``` + + + +```tsx +import { useAddShippingMethodToCart } from "medusa-react" +// ... + +const ShippingOptions = ({ cartId }: Props) => { + // ... + const addShippingMethod = useAddShippingMethodToCart(cartId) + + const handleAddShippingMethod = (option_id: string) => { + addShippingMethod.mutate({ + option_id, + }) + } + + // ... +} + +export default ShippingOptions +``` + -```jsx +```ts fetch(`/store/carts/${cartId}/shipping-methods`, { method: "POST", credentials: "include", @@ -204,17 +303,47 @@ To initialize the payment sessions, send a `POST` request to the [Initialize Pay -```jsx +```ts medusa.carts.createPaymentSessions(cartId) .then(({ cart }) => { console.log(cart.payment_sessions) }) ``` + + + +```tsx +import { PaymentSession } from "@medusajs/medusa" +import { useCart } from "medusa-react" +import { useEffect } from "react" + +const PaymentProviders = () => { + const { cart, startCheckout } = useCart() + + useEffect(() => { + startCheckout.mutate() + }, []) + + return ( +
    + {!cart?.payment_sessions.length && No payment providers} +
      + {cart?.payment_sessions.map((paymentSession: PaymentSession) => ( +
    • {paymentSession.provider_id}
    • + ))} +
    +
    + ) +} + +export default PaymentProviders +``` +
    -```jsx +```ts fetch(`/store/carts/${cartId}/payment-sessions`, { method: "POST", credentials: "include", @@ -237,7 +366,7 @@ When the customer chooses the payment provider they want to complete purchase wi -```jsx +```ts medusa.carts.setPaymentSession(cartId, { // retrieved from the payment session selected by the customer provider_id: paymentProviderId, @@ -247,10 +376,32 @@ medusa.carts.setPaymentSession(cartId, { }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const PaymentProviders = () => { + const { cart, startCheckout, pay } = useCart() + // ... + + const handleSetPaymentSession = (provider_id: string) => { + pay.mutate({ + provider_id, + }) + } + + // ... +} + +export default PaymentProviders +``` + -```jsx +```ts fetch(`/store/carts/${cartId}/payment-session`, { method: "POST", credentials: "include", @@ -290,7 +441,7 @@ If you need to update that data at any point before the purchase is made, send a -```jsx +```ts medusa.carts.updatePaymentSession(cartId, paymentProviderId, { data: { // pass any data you want to add in the `data` attribute @@ -303,12 +454,40 @@ medusa.carts.updatePaymentSession(cartId, paymentProviderId, { }) ``` + + + +```tsx +import { useUpdatePaymentSession, useCart } from "medusa-react" +// ... + +const PaymentProviders = () => { + const { cart } = useCart() + const updatePaymentSession = useUpdatePaymentSession(cart.id) + // ... + + const handleUpdatePaymentSession = ( + provider_id: string, + data: Record + ) => { + updatePaymentSession.mutate({ + provider_id, + data, + }) + } + + // ... +} + +export default PaymentProviders +``` + -```jsx +```ts fetch( `/store/carts/${cartId}/payment-sessions/${paymentProviderId}`, { @@ -348,17 +527,38 @@ To complete a cart, send a `POST` request to the [Complete a Cart](/api/store/#t -```jsx +```ts medusa.carts.complete(cartId) .then(({ type, data }) => { console.log(type, data) }) ``` + + + +```tsx +import { useCart } from "medusa-react" +// ... + +const Cart = () => { + const { completeCheckout } = useCart() + // ... + + const handleStartCheckout = () => { + startCheckout.mutate() + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}/complete`, { method: "POST", credentials: "include", diff --git a/docs/content/advanced/storefront/implement-claim-order.mdx b/docs/content/advanced/storefront/implement-claim-order.mdx index 0d964128d5..db3496a08d 100644 --- a/docs/content/advanced/storefront/implement-claim-order.mdx +++ b/docs/content/advanced/storefront/implement-claim-order.mdx @@ -44,10 +44,16 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + ### Handle Order Claim Request Event When the customer requests to claim the order, an event will be triggered. You should subscribe to this event to send a confirmation email to the customer when the event is triggered. @@ -71,7 +77,7 @@ To allow the customer to claim an order, send a request to the Claim an Order en -```tsx +```ts medusa.orders.claimOrders({ order_ids: [ order_id, @@ -88,7 +94,7 @@ medusa.orders.claimOrders({ -```tsx +```ts fetch(`/store/orders/batch/customer/token`, { method: "POST", credentials: "include", @@ -129,7 +135,7 @@ Then, you send a request to the Verify Claim Order endpoint: -```tsx +```ts medusa.orders.confirmRequest({ token, }) @@ -142,9 +148,31 @@ medusa.orders.confirmRequest({ ``` - + ```tsx +import { useGrantOrderAccess } from "medusa-react" + +const ClaimOrder = () => { + const grantOrderAccess = useGrantOrderAccess() + // ... + + const handleVerifyOrderClaim = (token: string) => { + grantOrderAccess.mutate(({ + token, + })) + } + + // ... +} + +export default ClaimOrder +``` + + + + +```ts fetch(`/store/orders/customer/confirm`, { method: "POST", credentials: "include", diff --git a/docs/content/advanced/storefront/use-discounts-in-checkout.mdx b/docs/content/advanced/storefront/use-discounts-in-checkout.mdx index b2a8273071..645df298ab 100644 --- a/docs/content/advanced/storefront/use-discounts-in-checkout.mdx +++ b/docs/content/advanced/storefront/use-discounts-in-checkout.mdx @@ -33,10 +33,18 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + +It's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider). + ### Previous Steps This document assumes you’ve already taken care of the add-to-cart flow. So, you should have a [cart created](/api/store/#tag/Cart/operation/PostCart) for the customer with at least [one product in it](/api/store/#tag/Cart/operation/PostCartsCartLineItems). @@ -54,7 +62,7 @@ You can add a discount to a customer’s cart by sending the [Update Cart reques -```jsx +```ts medusa.carts.update(cartId, { discounts: [ { @@ -71,10 +79,37 @@ medusa.carts.update(cartId, { }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const addDiscount = (code: string) => { + updateCart.mutate({ + discounts: [ + { + code, + }, + ], + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", @@ -218,7 +253,7 @@ You can remove a discount from a customer’s cart using the [Remove Discount re -```jsx +```ts medusa.carts.deleteDiscount(cartId, code) .then(({ cart }) => { console.log(cart.discounts) @@ -228,7 +263,7 @@ medusa.carts.deleteDiscount(cartId, code) -```jsx +```ts fetch(`/store/carts/${cartId}/discounts/${code}`, { method: "DELETE", credentials: "include", diff --git a/docs/content/advanced/storefront/use-gift-cards.mdx b/docs/content/advanced/storefront/use-gift-cards.mdx index 71b34f3965..df3566600d 100644 --- a/docs/content/advanced/storefront/use-gift-cards.mdx +++ b/docs/content/advanced/storefront/use-gift-cards.mdx @@ -29,10 +29,18 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + +For requests that use the cart, it's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider). + ### Previous Steps To use gift cards, you must have a gift card created first. You can follow this documentation to learn how to do it using the admin APIs. @@ -64,6 +72,36 @@ medusa.products.list({ }) ``` + + + +```tsx +import { Product } from "@medusajs/medusa" +import { useProducts } from "medusa-react" + +const GiftCard = () => { + const { products, isLoading } = useProducts({ + is_giftcard: true, + }) + + return ( +
    + {isLoading && Loading...} + {products && products.length > 0 && ( +
      + {products.map((product: Product) => ( +
    • {product.title}
    • + ))} +
    + )} + {products && !products.length && No Gift Cards} +
    + ) +} + +export default GiftCard +``` +
    @@ -118,6 +156,27 @@ medusa.giftCards.retrieve(code) }) ``` + + + +```tsx +import { useGiftCard } from "medusa-react" + +const GiftCard = () => { + const { gift_card, isLoading, isError } = useGiftCard("code") + + return ( +
    + {isLoading && Loading...} + {gift_card && {gift_card.value}} + {isError && Gift Card does not exist} +
    + ) +} + +export default GiftCard +``` +
    @@ -178,6 +237,33 @@ medusa.carts.update(cartId, { }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const setGiftCard = (code: string) => { + updateCart.mutate({ + gift_cards: [ + { + code, + }, + ], + }) + } + + // ... +} + +export default Cart +``` + diff --git a/docs/content/advanced/storefront/use-regions.mdx b/docs/content/advanced/storefront/use-regions.mdx index 64f0be708f..9d1598e734 100644 --- a/docs/content/advanced/storefront/use-regions.mdx +++ b/docs/content/advanced/storefront/use-regions.mdx @@ -29,10 +29,18 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + +For requests that use the cart, it's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider). + --- ## Show List of Regions @@ -44,7 +52,7 @@ You can retrieve available regions by sending a request to the [List Regions](/a -```tsx +```ts medusa.regions.list() .then(({ regions }) => { console.log(regions.length) @@ -53,9 +61,38 @@ medusa.regions.list() ``` - + ```tsx +import { Region } from "@medusajs/medusa" +import { useRegions } from "medusa-react" + +const Regions = () => { + const { regions, isLoading } = useRegions() + + return ( +
    + {isLoading && Loading...} + {regions?.length && ( +
      + {regions.map((region: Region) => ( +
    • + {region.name} +
    • + ))} +
    + )} +
    + ) +} + +export default Regions +``` + +
    + + +```ts fetch(`/store/regions`, { credentials: "include", }) @@ -84,7 +121,7 @@ For example: -```tsx +```ts medusa.products.list({ region_id: regionId, }) @@ -95,9 +132,32 @@ medusa.products.list({ ``` - + ```tsx +import { formatVariantPrice } from "medusa-react" + +const Product = () => { + // retrieve the region and variant(s) + // ... + + return ( + + {formatVariantPrice({ + variant, // ProductVariant + region, // Region + })} + + ) +} + +export default Product +``` + + + + +```ts fetch(`/store/products?region_id=${regionId}`, { credentials: "include", }) @@ -134,7 +194,7 @@ For example: -```tsx +```ts medusa.carts.update(cartId, { region_id: regionId, }) @@ -144,9 +204,32 @@ medusa.carts.update(cartId, { ``` - + ```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const changeRegionId = (region_id: string) => { + updateCart.mutate({ + region_id, + }) + } + + // ... +} + +export default Cart +``` + + + + +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", diff --git a/docs/content/advanced/storefront/use-sales-channels.mdx b/docs/content/advanced/storefront/use-sales-channels.mdx index 2b17601744..42e06becec 100644 --- a/docs/content/advanced/storefront/use-sales-channels.mdx +++ b/docs/content/advanced/storefront/use-sales-channels.mdx @@ -32,10 +32,18 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../../js-client/overview.md) and have [created an instance of the client](../../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../../medusa-react/overview.md#usage). + +For requests that use the cart, it's also assumed you already have [used CartProvider higher in your component tree](../../medusa-react/overview.md#cartprovider). + --- ## Filter Products by Sales Channel @@ -45,7 +53,7 @@ To filter products by a specific sales channel, pass the `sales_channel_id` quer -```jsx +```ts medusa.products.list({ sales_channel_id: [ salesChannelId, @@ -56,10 +64,42 @@ medusa.products.list({ }) ``` + + + +```tsx +import { Product } from "@medusajs/medusa" +import { useProducts } from "medusa-react" + +const Products = () => { + const { products, isLoading } = useProducts({ + sales_channel_id: [ + salesChannelId, + ], + }) + + return ( +
    + {isLoading && Loading...} + {products && products.length > 0 && ( +
      + {products.map((product: Product) => ( +
    • {product.title}
    • + ))} +
    + )} + {products && !products.length && No Products} +
    + ) +} + +export default Products +``` +
    -```jsx +```ts fetch(`/store/products?sales_channel_id[0]=${salesChannelId}`) .then((response) => response.json()) .then(({ products, limit, offset, count }) => { @@ -86,7 +126,7 @@ To associate a sales channel with a cart while creating it, you can pass the `sa -```jsx +```ts medusa.carts.create({ sales_channel_id: salesChannelId, }) @@ -95,10 +135,36 @@ medusa.carts.create({ }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + const { cart, createCart } = useCart() + + const handleCreateCart = () => { + createCart.mutate( + { + sales_channel_id: salesChannelId, + }, + { + onSuccess: ({ cart }) => localStorage.setItem("cart_id", cart.id), + } + ) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts`, { method: "POST", headers: { @@ -126,7 +192,7 @@ You can update the sales channel of an existing cart by passing the `sales_chann -```jsx +```ts medusa.carts.update(cartId, { sales_channel_id: salesChannelId, }) @@ -135,10 +201,33 @@ medusa.carts.update(cartId, { }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const changeSalesChannel = (salesChannelId: string) => { + updateCart.mutate({ + sales_channel_id: salesChannelId, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", headers: { diff --git a/docs/content/guides/carts-in-medusa.mdx b/docs/content/guides/carts-in-medusa.mdx index 979a74e2c9..72739ab0b8 100644 --- a/docs/content/guides/carts-in-medusa.mdx +++ b/docs/content/guides/carts-in-medusa.mdx @@ -17,10 +17,6 @@ This document does not cover implementing the checkout flow. You can refer to [t ::: -### Glossary - -- **Line Item**: When products are added to the cart in Medusa, they are referred to as line items. Line items have, by default, the same properties and attributes as a product. However, you can customize line items specifically for a cart if necessary. - --- ## Prerequisites @@ -33,10 +29,18 @@ It is also assumed you already have a storefront set up. It can be a custom stor ### JS Client -This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client and JavaScript’s Fetch API. +This guide includes code snippets to send requests to your Medusa server using Medusa’s JS Client, among other methods. If you follow the JS Client code blocks, it’s assumed you already have [Medusa’s JS Client installed](../js-client/overview.md) and have [created an instance of the client](../js-client/overview.md#configuration). +### Medusa React + +This guide also includes code snippets to send requests to your Medusa server using Medusa React, among other methods. + +If you follow the Medusa React code blocks, it's assumed you already have [Medusa React installed](../medusa-react/overview.md) and have [used MedusaProvider higher in your component tree](../medusa-react/overview.md#usage). + +It's also assumed you already have [used CartProvider higher in your component tree](../medusa-react/overview.md#cartprovider). + --- ## Create a Cart @@ -46,7 +50,7 @@ You can create a cart with the following code snippet: -```jsx +```ts medusa.carts.create() .then(({ cart }) => { localStorage.setItem("cart_id", cart.id) @@ -55,10 +59,34 @@ medusa.carts.create() }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + const { cart, createCart } = useCart() + + const handleCreateCart = () => { + createCart.mutate( + {}, // create an empty cart + { + onSuccess: ({ cart }) => localStorage.setItem("cart_id", cart.id), + } + ) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts`, { method: "POST", credentials: "include", @@ -94,6 +122,32 @@ medusa.carts.create({ }) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + const { cart, createCart } = useCart() + + const handleCreateCart = () => { + createCart.mutate( + { + region_id, + }, + { + onSuccess: ({ cart }) => localStorage.setItem("cart_id", cart.id), + } + ) + } + + // ... +} + +export default Cart +``` + @@ -138,7 +192,7 @@ You can retrieve the cart at any given point using its ID with the following cod -```jsx +```ts const id = localStorage.getItem("cart_id") if (id) { @@ -147,10 +201,25 @@ if (id) { } ``` + + + +```tsx +import { useGetCart } from "medusa-react" + +const Cart = () => { + const { cart, isLoading } = useGetCart(cart_id) + + // ... +} + +export default Cart +``` + -```jsx +```ts const id = localStorage.getItem("cart_id") if (id) { @@ -186,17 +255,40 @@ You can use the following snippet to update any of the cart’s data: -```jsx +```ts medusa.carts.update(cartId, { region_id, }) .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const changeRegionId = (region_id: string) => { + updateCart.mutate({ + region_id, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", @@ -229,17 +321,40 @@ You can do that using the same update operation: -```jsx +```ts medusa.carts.update(cartId, { customer_id, }) .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const changeCustomerId = (customer_id: string) => { + updateCart.mutate({ + customer_id, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", @@ -268,17 +383,40 @@ You can do that using the same update operation: -```jsx +```ts medusa.carts.update(cartId, { email: "user@example.com", }) .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useCart } from "medusa-react" + +const Cart = () => { + // ... + + const { updateCart } = useCart() + + const changeEmail = (email: string) => { + updateCart.mutate({ + email, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}`, { method: "POST", credentials: "include", @@ -313,6 +451,30 @@ medusa.carts.lineItems.create(cartId, { .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useCreateLineItem } from "medusa-react" + +const Cart = () => { + // ... + + const createLineItem = useCreateLineItem(cart_id) + + const handleAddItem = () => { + createLineItem.mutate({ + variant_id, + quantity, + }) + } + + // ... +} + +export default Cart +``` + @@ -356,17 +518,41 @@ To update a line item's quantity in the cart, you can use the following code sni -```jsx +```ts medusa.carts.lineItems.update(cartId, lineItemId, { quantity: 3, }) .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useUpdateLineItem } from "medusa-react" + +const Cart = () => { + // ... + + const updateLineItem = useUpdateLineItem(cart_id) + + const handleUpdateItem = () => { + updateLineItem.mutate({ + lineId, + quantity: 3, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}/line-items/${lineItemId}`, { method: "POST", credentials: "include", @@ -397,15 +583,38 @@ To delete a line item from the cart, you can use the following code snippet: -```jsx +```ts medusa.carts.lineItems.delete(cartId, lineItemId) .then(({ cart }) => setCart(cart)) ``` + + + +```tsx +import { useDeleteLineItem } from "medusa-react" + +const Cart = () => { + // ... + + const deleteLineItem = useDeleteLineItem(cart_id) + + const handleDeleteItem = () => { + deleteLineItem.mutate({ + lineId, + }) + } + + // ... +} + +export default Cart +``` + -```jsx +```ts fetch(`/store/carts/${cartId}/line-items/${lineItemId}`, { method: "DELETE", credentials: "include", diff --git a/docs/content/js-client/overview.md b/docs/content/js-client/overview.md index e365be4f2d..81277d018b 100644 --- a/docs/content/js-client/overview.md +++ b/docs/content/js-client/overview.md @@ -84,5 +84,5 @@ const medusa = new Medusa({ | ------------------- | ------------------------- | --------------------------------------------------------- | | `maxRetries` | `0` | The amount of times a request is retried. | | `baseUrl` | `'http://localhost:9000'` | The url to which requests are made to. | -| `apiKey` | `''` | Optional api key used for authenticating admin requests . | +| `apiKey` | `''` | Optional API key used for authenticating admin requests. | | `publishableApiKey` | `''` | Optional publishable API key used for storefront requests.| \ No newline at end of file diff --git a/docs/content/medusa-react/overview.md b/docs/content/medusa-react/overview.md index b4863eb5a1..f783e0411e 100644 --- a/docs/content/medusa-react/overview.md +++ b/docs/content/medusa-react/overview.md @@ -55,7 +55,7 @@ import React from "react" const queryClient = new QueryClient() -function App() { +const App = () => { return ( { @@ -451,7 +456,7 @@ import React from "react" const queryClient = new QueryClient() -function App() { +const App = () => { return (